﻿using LiJu.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LiJu.Common
{
    public static class Batch
    {
        //程序号
        public static int psetnumbers;
        //步骤号
        public static int stepnumbers;

        public static string stepnumberstype;

        //最小扭矩
        public static double mintorques;
        public static double maxtorques;
        public static double safetorques;
        public static double targettorques;
        public static double anglethresholds;
        public static double minangles;
        public static double maxangles;
        public static double safeangles;
        public static double targetangles;
        public static double speeds;

        public static List<double> batchlist = new List<double>();

        public static List<ParameterManagerModel> parameterManagerModels = new List<ParameterManagerModel>();

        /// <summary>
        /// 返回的参数集合
        /// </summary>
        public static List<TightenModel> tightenModels = new List<TightenModel>();

        /// <summary>
        /// 连接状态,NUll->未连接，包含有错误则连接失败，有连接成功则正确
        /// </summary>
        public static string ConnectionState;

        /// <summary>
        /// 执行状态
        /// </summary>
        public static string ExecuteState;

        /// <summary>
        /// 曲线力矩数据
        /// </summary>
        public static List<double> TorqueResultData = new List<double>();
        /// <summary>
        /// 曲线角度数据
        /// </summary>
        public static List<double> AngleDataResultData = new List<double>();
        /// <summary>
        /// 曲线时间系数
        /// </summary>
        public static double timefactor = 0;
        /// <summary>
        /// 曲线扭矩系数
        /// </summary>
        public static double torquefactor = 0;
        /// <summary>
        /// 曲线角度系数
        /// </summary>
        public static double anglefactor = 0;
        /// <summary>
        /// 圈数转完结果时间
        /// </summary>
        private static DateTime cycleReusltTime = DateTime.Now;

        public static Action<List<double>, List<double>, double> SaveCurveAction;

        static string contents = "";

        public static List<string> stepidlist = new List<string>();//任务号，步骤号

        public static List<string> taskidlist = new List<string>();

        public static DataTable StepDataTableData;
        public static DataTable TaskDataTableData;
        public static DataRow TaskDataRow;
        public static DataRow StepDataRow;

        #region TCP的变量

        //是否启动 连接了
        public static bool isMonitor = false;
        //线程 用于监听服务端 发来的消息
        static Thread th;
        //客户端对象
        static TcpClient tcpclient;
        //创建 循环发送线程 懒得起名字
        static Thread thread;

        public static string ipaddress;
        public static int ipport;


        #endregion

        #region Action

        public static void InitDataTableData()
        {
            StepDataTableData = new DataTable();

            StepDataTableData.Columns.Add("Step", typeof(string));
            StepDataTableData.Columns.Add("Lap", typeof(string));
            StepDataTableData.Columns.Add("Speed", typeof(string));

            StepDataTableData.Columns.Add("MiniTorqueLength", typeof(string));
            StepDataTableData.Columns.Add("MaxTorqueLength", typeof(string));
            StepDataTableData.Columns.Add("SafeTorqueLength", typeof(string));

            StepDataTableData.Columns.Add("TargetTorqueLength", typeof(string));
            StepDataTableData.Columns.Add("MiniAngle", typeof(string));
            StepDataTableData.Columns.Add("MaxAngle", typeof(string));

            StepDataTableData.Columns.Add("SafeAngle", typeof(string));
            StepDataTableData.Columns.Add("TargetAngle", typeof(string));

            StepDataTableData.Columns.Add("Anglethreshold", typeof(string));

            StepDataTableData.Columns.Add("StepType", typeof(string));
            StepDataTableData.Columns.Add("TighteningType", typeof(string));
            //StepDataRow = StepDataTableData.NewRow();


            TaskDataTableData = new DataTable();
            TaskDataTableData.Columns.Add("Content", typeof(string));
            //TaskDataRow = TaskDataTableData.NewRow();
        }


        /// <summary>
        /// 链接
        /// </summary>
        /// <param name="ipaddress">IP地址</param>
        /// <param name="ipport">端口</param>
        public static void Connection(string ipaddress, string ipport)
        {
            //InitDataTableData();//测试用
            //判断是否连接了
            if (isMonitor == false)
            {
                try
                {
                    //创建客户端对象 初始化
                    tcpclient = new TcpClient();
                    //连接服务端
                    tcpclient.Connect(ipaddress, System.Convert.ToInt32(ipport));
                    /* NetworkStream strem = client.GetStream();
                    string str = this.textBox1.Text.Trim();
                    byte[] b = Encoding.UTF8.GetBytes(str);
                    strem.Write(b, 0, b.Length);
                    strem.Close();
                    client.Close();*/

                    //初始化 监听服务端回传消息 线程
                    th = new Thread(Recive);
                    //设置 后台线程
                    th.IsBackground = true;
                    //启动线程 传递对象
                    th.Start(tcpclient);

                    //启动监听
                    isMonitor = true;
                    //Connectionbutton.Text = "关闭连接";
                    ConnectionState = "连接成功";
                    int state = BLL.Bll.UpdateCommunicateOnlineData("电批", "是");
                    if (state > 0)
                    {

                    }
                    //连接成功 设置控件不可用
                    //IPtextBox.Enabled = false;
                    //PorttextBox.Enabled = false;
                    Debug.WriteLine("ConnectionState->" + ConnectionState);
                }
                catch (Exception ex)
                {
                    //MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    ConnectionState = "错误" + ex.Message.ToString();
                    Debug.WriteLine("ConnectionState->" + ConnectionState);
                }
            }
            else
            {
                //关闭监听
                tcpclient.Close();
                try
                {
                    if (thread != null)
                    {
                        BLL.Bll.UpdateCommunicateOnlineData("电批", "否");
                        thread.Abort();
                        //jytAutoSend.Text = "循环发送";

                    }
                }
                catch
                {

                }
                isMonitor = false;
                //Connectionbutton.Text = "连接";
                ////设置控件可用
                //IPtextBox.Enabled = true;
                //PorttextBox.Enabled = true;
            }
        }

        // 线程方法 获取服务端回传 消息
        static void Recive(object client)
        {
            NetworkStream reciveStream = ((TcpClient)client).GetStream();
            while (true)
            {
                try
                {
                    //NetworkStream nss = ((TcpClient)client).GetStream();
                    byte[] data2 = new byte[1024 * 1024];//存储服务端发送过来的数据
                    int _length = reciveStream.Read(data2, 0, data2.Length);
                    if (_length > 0)
                    {
                        string msg = Encoding.Default.GetString(data2, 0, _length);

                        Debug.WriteLine("msg------>" + msg);

                        #region 获取曲线
                        //最后拧紧结果返回，获取最后拧紧结果时间cycleReusltTime
                        if (msg.Contains("0061001"))
                        {
                            string tempStr = null;
                            for (int i = 176; i < 176 + 19; i++)
                            {
                                tempStr += Convert.ToChar(data2[i]).ToString();
                            }
                            if (tempStr[10] == ':')
                            {
                                tempStr = tempStr.Remove(10, 1);
                                tempStr = tempStr.Insert(10, " ");
                            }
                            if (DateTime.TryParse(tempStr, out DateTime time))
                            {
                                cycleReusltTime = time;
                            }
                        }
                        //最后拧紧曲线数据
                        else if (msg.Contains("7410001"))
                        {
                            //校验曲线数据,7410为曲线结果返回命令头
                            if (data2[4] == 0X37 && data2[5] == 0X34 && data2[6] == 0X31 && data2[7] == 0X30)
                            {
                                string lengthStr = null;
                                int length = 0;
                                for (int i = 0; i < 4; i++)
                                {
                                    lengthStr += Convert.ToChar(data2[i]).ToString();
                                }
                                if (int.TryParse(lengthStr, out int lengthValue))
                                {
                                    length = lengthValue;
                                }
                                if (length > 91)
                                {
                                    //获取曲线包数组
                                    byte[] curveArray = data2.Skip(91).Take(length - 91).ToArray();
                                    //获取时间系数，力矩系数和角度系数
                                    if (timefactor == 0 && torquefactor == 0 && anglefactor == 0)
                                    {
                                        string factorStr = null;
                                        for (int i = 31; i < 31 + 14; i++)
                                        {
                                            factorStr += Convert.ToChar(data2[i]).ToString();
                                        }
                                        if (double.TryParse(factorStr, out double timeValue))
                                        {
                                            timefactor = timeValue;
                                        }


                                        factorStr = null;
                                        for (int i = 47; i < 47 + 14; i++)
                                        {
                                            factorStr += Convert.ToChar(data2[i]).ToString();
                                        }
                                        if (double.TryParse(factorStr, out double torqueValue))
                                        {
                                            torquefactor = torqueValue;
                                        }

                                        factorStr = null;
                                        for (int i = 63; i < 63 + 14; i++)
                                        {
                                            factorStr += Convert.ToChar(data2[i]).ToString();
                                        }
                                        if (double.TryParse(factorStr, out double angleValue))
                                        {
                                            anglefactor = angleValue;
                                        }
                                    }
                                    if (curveArray.Length > 9 && (timefactor != 0 && torquefactor != 0 || anglefactor != 0))
                                    {
                                        try
                                        {
                                            //第一步，将FFFE替换成00，将FFFF替换成FF
                                            List<byte> curveList = new List<byte>();
                                            for (int i = 0; i < curveArray.Length; i++)
                                            {
                                                if (curveArray[i] == 0XFF && curveArray[i + 1] == 0xFF)
                                                {
                                                    curveList.Add(0XFF);
                                                    i++;
                                                }
                                                else if (curveArray[i] == 0XFF && curveArray[i + 1] == 0xFE)
                                                {
                                                    curveList.Add(0X00);
                                                    i++;
                                                }
                                                else
                                                {
                                                    curveList.Add(curveArray[i]);
                                                }
                                            }
                                            byte[] targetArray = curveList.ToArray();

                                            //第二步，所有字节数减一
                                            for (int i = 0; i < targetArray.Length; i++)
                                            {
                                                targetArray[i] = (byte)(targetArray[i] - 1);
                                            }

                                            ////第三步，力矩与角度数组高位与地位互换
                                            //byte[] sourceArray = targetArray;
                                            //Array.Clear(targetArray, 0, targetArray.Length);
                                            //int j = 0;
                                            //for (int i = 0; i < sourceArray.Length; i++)
                                            //{
                                            //    targetArray[j] = sourceArray[j + 1];
                                            //    targetArray[j + 1] = sourceArray[j];
                                            //    targetArray[j + 2] = sourceArray[j + 5];
                                            //    targetArray[j + 3] = sourceArray[j + 4];
                                            //    targetArray[j + 4] = sourceArray[j + 3];
                                            //    targetArray[j + 5] = sourceArray[j + 2];
                                            //    j = j + 6;
                                            //    if (j >= sourceArray.Length - 1)
                                            //    {
                                            //        break;
                                            //    }
                                            //}

                                            //第四步，力矩(2字节)，角度(4字节)和时间乘以它们的系数，得到实际值
                                            int j = 0;
                                            for (int i = 0; i < targetArray.Length; i++)
                                            {
                                                List<byte> torque = new List<byte>() { targetArray[j], targetArray[j + 1] };
                                                double torqueValue = BitConverter.ToInt16(torque.ToArray(), 0) * torquefactor;
                                                TorqueResultData.Add(Math.Round(torqueValue, 1));

                                                List<byte> angle = new List<byte>() { targetArray[j + 2], targetArray[j + 3], targetArray[j + 4], targetArray[j + 5] };
                                                double angleValue = BitConverter.ToInt32(angle.ToArray(), 0) * anglefactor;
                                                AngleDataResultData.Add(Math.Round(angleValue, 1));
                                                j = j + 6;
                                                if (j > targetArray.Length - 6)
                                                {
                                                    break;
                                                }
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            Console.WriteLine($"曲线力矩，角度值转换异常->{ex.Message}");
                                        }
                                    }
                                }
                            }
                        }
                        //Cycle result data，圈数完成结果数据
                        else if (msg.Contains("7406001"))
                        {
                            if (TorqueResultData.Count > 0 && AngleDataResultData.Count > 0)
                            {
                                for (int i = AngleDataResultData.Count - 1; i > 0; i--)
                                {
                                    if (AngleDataResultData[i] == 0)
                                    {
                                        AngleDataResultData.RemoveAt(AngleDataResultData.Count - 1);
                                        TorqueResultData.RemoveAt(TorqueResultData.Count - 1);
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                if (AngleDataResultData.Count > 0)
                                {
                                    //double curveSpend = (DateTime.Now - cycleReusltTime).TotalSeconds;
                                    //double timeSpendStep = curveSpend / AngleDataResultData.Count;
                                    //if(timefactor>0)
                                    //{
                                    //    timeSpendStep = timefactor * AngleDataResultData.Count;
                                    //}
                                    Debug.WriteLine($"曲线时间系数->{timefactor}");
                                    SaveCurveAction?.Invoke(TorqueResultData, AngleDataResultData, timefactor);
                                    TorqueResultData.Clear();
                                    AngleDataResultData.Clear();
                                }
                            }
                        }
                        #endregion

                        //调用 写入数据方法 把数据信息转成 选定的编码格式数据
                        AddData(("从ip：" + ((TcpClient)client).Client.RemoteEndPoint.ToString() + "收到了数据："), System.Text.Encoding.Default.GetBytes(msg));
                    }
                    else
                    {
                        try
                        {

                            if (((TcpClient)client) != null && ((TcpClient)client).Connected)
                            {
                                // NetworkStream ns = ((TcpClient)client).GetStream();
                                //ns.Close();
                                reciveStream.Close();
                                ((TcpClient)client).Close();
                            }
                        }
                        catch (Exception ex)
                        {
                            //MessageBox.Show(ex.Message, "错误");
                            ConnectionState = "错误" + ex.Message.ToString();
                            Debug.WriteLine("ConnectionState->" + ConnectionState);
                        }

                    }

                }
                catch
                {
                    th.Abort();

                }
            }
        }

        //处理返回值 将返回的数据 转成jytCodingtype 选择的编码格式
        public static void AddData(string ClientIPtxt, byte[] data)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sb.AppendFormat("{0:x2}" + " ", data[i]);
            }
            AddContent(ClientIPtxt, sb.ToString().ToUpper());
        }


        private static void AddContent(string ClientIPtxt, string content)
        {
            //if (RespecttextBox.Text.Length > 0)
            //{
            //    RespecttextBox.AppendText("\r\n");
            //}
            // 文本框输出返回内容
            //RespecttextBox.AppendText(ClientIPtxt + content);

            contents = content;
            Debug.WriteLine(ClientIPtxt + content);

            if (content.Contains("30 30 32 34 30 30 30 35 30 30 31 20 20 20 20 20 20 20 20 20 37 34 31 34 00 "))//写入成功
            {
                if (parameterManagerModels.Count > 0)
                {
                    parameterManagerModels.Clear();
                }
                ParameterManagerModel parameterManagerModel = new ParameterManagerModel();
                //程序号
                parameterManagerModel.Psetnumber = psetnumbers;

                //最小扭矩
                parameterManagerModel.Mintorque = mintorques;
                parameterManagerModel.Maxtorque = maxtorques;
                parameterManagerModel.Safetorque = safetorques;
                parameterManagerModel.Targettorque = targettorques;
                parameterManagerModel.Minangle = minangles;
                parameterManagerModel.Maxangle = maxangles;
                parameterManagerModel.Safeangle = safeangles;
                parameterManagerModel.Targetangle = targetangles;
                parameterManagerModel.Speed = speeds;

                parameterManagerModels.Add(parameterManagerModel);
            }

            if (content.Contains("30 32 33 31 30 30 36 31 30 30 31 ") && content.Length == 696)//拧紧结果
            {
                //string tighten = content.Substring(0,437);
                //string tightenresult= tighten.Substring(437 - 24);
                //if (tightenresult.Contains("31 35 30 30 30 30 30 30"))//31 35 30 30 30 30 30 30
                //{
                //}

                //List<TightenModel> 
                tightenModels.Clear();
                TightenModel tightenModel = new TightenModel();
                #region

                //string totalstring = "30 32 33 31 30 30 36 31 30 30 31 20 20 20 20 20 20 20 20 20 30 31 30 30 30 30 30 32 30 31 30 33 43 56 49 52 20 49 49 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 30 34 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 30 35 30 30 30 36 30 30 31 30 37 30 30 30 31 30 38 30 30 30 30 30 39 30 31 30 30 31 31 31 31 32 30 30 30 35 31 30 31 33 30 30 30 36 39 30 31 34 30 30 30 36 30 30 31 35 30 30 30 30 30 30 31 36 30 30 30 30 30 31 37 30 30 30 30 30 31 38 30 30 30 30 30 31 39 30 30 30 30 30 32 30 32 30 32 34 2D 30 35 2D 32 35 3A 31 34 3A 31 37 3A 30 37 32 31 32 30 32 34 2D 30 35 2D 32 35 3A 31 30 3A 32 33 3A 34 30 32 32 30 32 33 30 30 30 30 30 30 39 36 37 36 00 ";

                string befor = "30 32 33 31 30 30 36 31 30 30 31 20 20 20 20 20 20 20 20 20 30 31 30 30 30 30 30 32 30 31 30 33 43 56 49 52 20 49 49 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 30 34 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 30 35 30 30 30 36 30 30 31 30 37 30 30 30 31 30 38 30 30 30 30 ";

                string after = "32 33 30 30 30 30 30 30 39 36 37 36 00 ";

                int totalstringlength = content.Length;//696

                int beforlength = befor.Length;//315

                int afterlength = after.Length;//39

                Debug.WriteLine("");

                string usestring = content.Remove(0, 315);

                //09
                string newstr09 = usestring.Substring(0, 9);
                string[] parts09 = newstr09.Split(' ');
                string newstring09 = "";
                List<string> list09 = new List<string>();
                for (int i = 0; i < parts09.Length; i++)
                {
                    if (!string.IsNullOrEmpty(parts09[i]))
                    {
                        list09.Add(parts09[i]);
                        int number = Convert.ToInt32(parts09[i]) - 30;
                        string hexStr = number.ToString("X");
                        newstring09 += hexStr;
                    }
                }
                string resultstr09 = newstring09.Remove(0, 2);
                if (resultstr09 == "0")
                {
                    //NG
                    tightenModel.TighteningStatus = "NG";
                }
                else
                {
                    //OK
                    tightenModel.TighteningStatus = "OK";
                }
                Debug.WriteLine("TighteningStatus->" + tightenModel.TighteningStatus);

                //10

                string newstr10 = usestring.Substring(9, 9);
                string[] parts10 = newstr10.Split(' ');
                string newstring10 = "";
                List<string> list10 = new List<string>();
                for (int i = 0; i < parts10.Length; i++)
                {
                    if (!string.IsNullOrEmpty(parts10[i]))
                    {
                        list10.Add(parts10[i]);
                        int number = Convert.ToInt32(parts10[i]) - 30;
                        string hexStr = number.ToString("X");
                        newstring10 += hexStr;
                    }
                }
                string resultstr10 = newstring10.Remove(0, 2);
                if (resultstr10 == "0")
                {
                    //Low
                    tightenModel.TorqueStatus = "Low";
                }
                else if (resultstr10 == "1")
                {
                    //OK
                    tightenModel.TorqueStatus = "OK";
                }
                else
                {
                    //Hight
                    tightenModel.TorqueStatus = "Hight";
                }

                Debug.WriteLine("TorqueStatus->" + tightenModel.TorqueStatus);

                //11

                string newstr11 = usestring.Substring(18, 9);
                string[] parts11 = newstr11.Split(' ');
                string newstring11 = "";
                List<string> list11 = new List<string>();
                for (int i = 0; i < parts11.Length; i++)
                {
                    if (!string.IsNullOrEmpty(parts11[i]))
                    {
                        list11.Add(parts11[i]);
                        int number = Convert.ToInt32(parts11[i]) - 30;
                        string hexStr = number.ToString("X");
                        newstring11 += hexStr;
                    }
                }
                string resultstr11 = newstring11.Remove(0, 2);
                if (resultstr11 == "0")
                {
                    //Low
                    tightenModel.AngleStatus = "Low";
                }
                else if (resultstr11 == "1")
                {
                    //OK
                    tightenModel.AngleStatus = "OK";
                }
                else
                {
                    //Hight
                    tightenModel.AngleStatus = "Hight";
                }
                Debug.WriteLine("TorqueStatus->" + tightenModel.TorqueStatus);
                //12
                string newstr12 = usestring.Substring(27, 24);
                string[] parts12 = newstr12.Split(' ');
                string newstring12 = "";
                List<string> list12 = new List<string>();
                for (int i = 0; i < parts12.Length; i++)
                {
                    if (!string.IsNullOrEmpty(parts12[i]))
                    {
                        list12.Add(parts12[i]);
                        int number = Convert.ToInt32(parts12[i]) - 30;
                        string hexStr = number.ToString("X");
                        newstring12 += hexStr;
                    }
                }
                string resultstr12 = newstring12.Remove(0, 2);
                double resultdou12 = System.Convert.ToDouble(resultstr12.ToString()) / 100;

                tightenModel.TorqueMinLimit = resultdou12.ToString();
                Debug.WriteLine("TorqueMinLimit->" + tightenModel.TorqueMinLimit);
                //Debug.WriteLine("");
                //13

                string newstr13 = usestring.Substring(51, 24);
                string[] parts13 = newstr13.Split(' ');
                string newstring13 = "";
                List<string> list13 = new List<string>();
                for (int i = 0; i < parts13.Length; i++)
                {
                    if (!string.IsNullOrEmpty(parts13[i]))
                    {
                        list13.Add(parts13[i]);
                        int number = Convert.ToInt32(parts13[i]) - 30;
                        string hexStr = number.ToString("X");
                        newstring13 += hexStr;
                    }
                }
                string resultstr13 = newstring13.Remove(0, 2);
                double resultdou13 = System.Convert.ToDouble(resultstr13.ToString()) / 100;
                tightenModel.TorqueMaxLimit = resultdou13.ToString();
                Debug.WriteLine("TorqueMaxLimit->" + tightenModel.TorqueMaxLimit);
                //Debug.WriteLine("");

                //14
                string newstr14 = usestring.Substring(75, 24);
                string[] parts14 = newstr14.Split(' ');
                string newstring14 = "";
                List<string> list14 = new List<string>();
                for (int i = 0; i < parts14.Length; i++)
                {
                    if (!string.IsNullOrEmpty(parts14[i]))
                    {
                        list14.Add(parts14[i]);
                        int number = Convert.ToInt32(parts14[i]) - 30;
                        string hexStr = number.ToString("X");
                        newstring14 += hexStr;
                    }
                }
                string resultstr14 = newstring14.Remove(0, 2);
                double resultdou14 = System.Convert.ToDouble(resultstr14.ToString()) / 100;
                tightenModel.TorqueFinalTarget = resultdou14.ToString();
                Debug.WriteLine("TorqueFinalTarget->" + tightenModel.TorqueFinalTarget);
                //Debug.WriteLine("");
                //15
                string newstr15 = usestring.Substring(99, 24);
                string[] parts15 = newstr15.Split(' ');
                string newstring15 = "";
                List<string> list15 = new List<string>();
                for (int i = 0; i < parts15.Length; i++)
                {
                    if (!string.IsNullOrEmpty(parts15[i]))
                    {
                        list15.Add(parts15[i]);
                        int number = Convert.ToInt32(parts15[i]) - 30;
                        string hexStr = number.ToString("X");
                        newstring15 += hexStr;
                    }
                }
                string resultstr15 = newstring15.Remove(0, 2);
                double resultdou15 = System.Convert.ToDouble(resultstr15.ToString()) / 100;
                tightenModel.Torque = resultdou15.ToString();
                Debug.WriteLine("Torque->" + tightenModel.Torque);
                //16

                string newstr16 = usestring.Substring(123, 21);
                string[] parts16 = newstr16.Split(' ');
                string newstring16 = "";
                List<string> list16 = new List<string>();
                for (int i = 0; i < parts16.Length; i++)
                {
                    if (!string.IsNullOrEmpty(parts16[i]))
                    {
                        list16.Add(parts16[i]);
                        int number = Convert.ToInt32(parts16[i]) - 30;
                        string hexStr = number.ToString("X");
                        newstring16 += hexStr;
                    }
                }
                string resultstr16 = newstring16.Remove(0, 2);
                double resultdou16 = System.Convert.ToDouble(resultstr16.ToString()) / 10;

                tightenModel.AngleMin = resultdou16.ToString();
                Debug.WriteLine("AngleMin->" + tightenModel.AngleMin);
                //Debug.WriteLine("");

                //17

                string newstr17 = usestring.Substring(144, 21);
                string[] parts17 = newstr17.Split(' ');
                string newstring17 = "";
                List<string> list17 = new List<string>();
                for (int i = 0; i < parts17.Length; i++)
                {
                    if (!string.IsNullOrEmpty(parts17[i]))
                    {
                        list17.Add(parts17[i]);
                        int number = Convert.ToInt32(parts17[i]) - 30;
                        string hexStr = number.ToString("X");
                        newstring17 += hexStr;
                    }
                }
                string resultstr17 = newstring17.Remove(0, 2);
                double resultdou17 = System.Convert.ToDouble(resultstr17.ToString()) / 10;
                tightenModel.AngleMax = resultdou17.ToString();
                Debug.WriteLine("AngleMax->" + tightenModel.AngleMax);
                //Debug.WriteLine("");

                //18

                string newstr18 = usestring.Substring(165, 21);
                string[] parts18 = newstr18.Split(' ');
                string newstring18 = "";
                List<string> list18 = new List<string>();
                for (int i = 0; i < parts18.Length; i++)
                {
                    if (!string.IsNullOrEmpty(parts18[i]))
                    {
                        list18.Add(parts18[i]);
                        int number = Convert.ToInt32(parts18[i]) - 30;
                        string hexStr = number.ToString("X");
                        newstring18 += hexStr;
                    }
                }
                string resultstr18 = newstring18.Remove(0, 2);
                double resultdou18 = System.Convert.ToDouble(resultstr18.ToString()) / 10;
                tightenModel.FinalAngleTarget = resultdou18.ToString();
                Debug.WriteLine("FinalAngleTarget->" + tightenModel.FinalAngleTarget);
                //Debug.WriteLine("");

                //19

                string newstr19 = usestring.Substring(186, 21);
                string[] parts19 = newstr19.Split(' ');
                string newstring19 = "";
                List<string> list19 = new List<string>();
                for (int i = 0; i < parts19.Length; i++)
                {
                    if (!string.IsNullOrEmpty(parts19[i]))
                    {
                        list19.Add(parts19[i]);
                        int number = Convert.ToInt32(parts19[i]) - 30;
                        string hexStr = number.ToString("X");
                        newstring19 += hexStr;
                    }
                }
                string resultstr19 = newstring19.Remove(0, 2);
                double resultdou19 = System.Convert.ToDouble(resultstr19.ToString());
                tightenModel.Angle = resultdou19.ToString();
                Debug.WriteLine("Angle->" + tightenModel.Angle);
                //20

                //string a = "32 30 32 30 32 34 2D 30 35 2D 32 35 3A 31 34 3A 31 37 3A 30 37 ";
                //int al = a.Length;//63
                //Debug.WriteLine("");

                //string newstr20 = usestring.Substring(207, 63);
                //string[] parts20 = newstr20.Split(' ');
                //string newstring20 = "";
                //List<string> list20 = new List<string>();
                //for (int i = 0; i < parts20.Length; i++)
                //{
                //    if (!string.IsNullOrEmpty(parts20[i]))
                //    {
                //        list20.Add(parts20[i]);
                //        int number = Convert.ToInt32(parts20[i]) - 30;
                //        string hexStr = number.ToString("X");
                //        newstring20 += hexStr;
                //    }
                //}
                //string resultstr20 = newstring20.Remove(0, 2);
                //double resultdou20 = System.Convert.ToDouble(resultstr20) / 100;
                //Debug.WriteLine("");

                //21

                //string newstr21 = usestring.Substring(270, 63);
                //string[] parts21 = newstr21.Split(' ');
                //string newstring21 = "";
                //List<string> list21 = new List<string>();
                //for (int i = 0; i < parts21.Length; i++)
                //{
                //    if (!string.IsNullOrEmpty(parts21[i]))
                //    {
                //        list21.Add(parts21[i]);
                //        int number = Convert.ToInt32(parts21[i]) - 30;
                //        string hexStr = number.ToString("X");
                //        newstring21 += hexStr;
                //    }
                //}
                //string resultstr21 = newstring21.Remove(0, 2);
                //double resultdou21 = System.Convert.ToDouble(resultstr21) / 100;
                //Debug.WriteLine("");

                //22

                string newstr22 = usestring.Substring(333, 9);
                string[] parts22 = newstr22.Split(' ');
                string newstring22 = "";
                List<string> list22 = new List<string>();
                for (int i = 0; i < parts22.Length; i++)
                {
                    if (!string.IsNullOrEmpty(parts22[i]))
                    {
                        list22.Add(parts22[i]);
                        int number = Convert.ToInt32(parts22[i]) - 30;
                        string hexStr = number.ToString("X");
                        newstring22 += hexStr;
                    }
                }
                string resultstr22 = newstring22.Remove(0, 2);

                double resulTighteningStatustdou22 = System.Convert.ToDouble(resultstr22);

                //Debug.WriteLine("Angle->" + tightenModel.Angle);

                if (resultstr22 == "0")
                {
                    //NG
                    tightenModel.BatchStatus = "NG";

                }
                else if (resultstr22 == "1")
                {
                    //OK
                    tightenModel.BatchStatus = "OK";
                }
                else
                {
                    //电批没有使用
                    tightenModel.BatchStatus = "电批没有使用";
                }
                Debug.WriteLine("BatchStatus->" + tightenModel.BatchStatus);
                //23 TighteningID
                string newstr23 = usestring.Substring(342, 36);
                string[] parts23 = newstr23.Split(' ');
                string newstring23 = "";
                List<string> list23 = new List<string>();
                for (int i = 0; i < parts23.Length; i++)
                {
                    if (!string.IsNullOrEmpty(parts23[i]))
                    {
                        list23.Add(parts23[i]);
                        int number = Convert.ToInt32(parts23[i]) - 30;
                        string hexStr = number.ToString("X");
                        newstring23 += hexStr;
                    }
                }
                string resultstr23 = newstring23.Remove(0, 2);
                double resultdou23 = System.Convert.ToDouble(resultstr23.ToString());
                tightenModel.TighteningID = resultdou23.ToString();
                Debug.WriteLine("TighteningID->" + tightenModel.TighteningID);
                tightenModels.Add(tightenModel);

                #endregion

            }


            if (content.Length == 81 && content == "30 30 32 36 30 30 30 34 30 30 31 20 20 20 20 20 20 20 20 20 37 34 31 32 30 32 00 ")
            {
                //没有程序
            }
            if (content.Contains("30 32 38 33 37 34 31 33 ") && content.Length == 852)//读取程序
            {
                //string getdata = "30 32 38 33 37 34 31 33 30 30 31 20 20 20 20 20 20 20 20 20 30 31 30 31 30 32 30 30 31 30 33 30 32 30 34 44 20 30 35 3F 3F 30 36 30 30 30 30 30 30 30 37 30 30 30 30 30 30 30 38 30 30 30 30 30 30 30 39 30 30 30 30 30 30 31 30 30 30 30 30 30 30 31 31 30 30 30 30 30 30 31 32 30 30 30 30 30 30 31 33 30 30 30 30 30 30 31 34 30 30 30 30 30 30 31 35 30 30 30 30 30 30 31 36 30 30 30 30 30 30 31 37 30 30 30 30 30 30 31 38 30 30 30 30 30 30 31 39 30 30 30 30 30 30 32 30 30 30 30 30 30 30 32 31 30 30 30 30 34 30 32 32 30 30 30 30 30 30 32 33 30 30 30 30 30 30 32 34 30 30 32 35 30 30 30 30 30 30 32 36 30 30 30 30 30 30 32 37 30 30 30 30 32 38 30 30 30 30 32 39 30 30 30 30 30 30 33 30 30 30 30 30 30 30 33 31 30 30 30 30 30 30 33 32 43 57 33 33 54 33 34 30 30 30 33 35 30 33 36 4E 6D 20 20 33 37 32 30 32 34 2D 30 36 2D 30 34 3A 31 37 3A 35 35 3A 34 31 00 ";

                string Tighteningstrategytype = content.Substring(111, 12);//005
                string newstrTighteningstrategytype = Tighteningstrategytype.Substring(6, 2);
                byte byteTighteningstrategytype = Convert.ToByte(newstrTighteningstrategytype, 16);
                char[] TighteningstrategytypecharArray = newstrTighteningstrategytype.ToCharArray();
                string lengthTighteningstrategytype = Convert.ToChar(byteTighteningstrategytype).ToString();
                if (lengthTighteningstrategytype == "1")
                {
                    //角度+扭矩
                }
                switch (lengthTighteningstrategytype)
                {
                    case "1":
                        break;
                    case "":
                        break;
                    default:
                        break;
                }

                string mintorque = content.Substring(123, 24);
                int mintorquel = mintorque.Length;
                string newstrmintorque = mintorque.Substring(6, 18);
                string[] partsmintorque = newstrmintorque.Split(' ');
                string newstringmintorque = "";
                List<string> listmintorque = new List<string>();
                for (int i = 0; i < partsmintorque.Length; i++)
                {
                    if (!string.IsNullOrEmpty(partsmintorque[i]))
                    {
                        listmintorque.Add(partsmintorque[i]);
                        int number = Convert.ToInt32(partsmintorque[i]) - 30;
                        string hexStr = number.ToString("X");
                        newstringmintorque += hexStr;
                    }
                }
                string resultstrmintorque = newstringmintorque;
                double doubleresultstrmintorque = System.Convert.ToDouble(resultstrmintorque) / 100;

                mintorques = doubleresultstrmintorque;



                string maxtorque = content.Substring(147, 24); int maxtorquel = maxtorque.Length;
                string newstrmaxtorque = maxtorque.Substring(6, 18);
                string[] partsmaxtorque = newstrmaxtorque.Split(' ');
                string newstringmaxtorque = "";
                List<string> listmaxtorque = new List<string>();
                for (int i = 0; i < partsmaxtorque.Length; i++)
                {
                    if (!string.IsNullOrEmpty(partsmaxtorque[i]))
                    {
                        listmaxtorque.Add(partsmaxtorque[i]);
                        int number = Convert.ToInt32(partsmaxtorque[i]) - 30;
                        string hexStr = number.ToString("X");
                        newstringmaxtorque += hexStr;
                    }
                }
                string resultstrmaxtorque = newstringmaxtorque;
                double doubleresultstrmaxtorque = System.Convert.ToDouble(resultstrmaxtorque) / 100;
                maxtorques = doubleresultstrmaxtorque;



                string safetorque = content.Substring(171, 24);
                string newstrsafetorque = safetorque.Substring(6, 18);
                string[] partssafetorque = newstrsafetorque.Split(' ');
                string newstringsafetorque = "";
                List<string> listsafetorque = new List<string>();
                for (int i = 0; i < partssafetorque.Length; i++)
                {
                    if (!string.IsNullOrEmpty(partssafetorque[i]))
                    {
                        listsafetorque.Add(partssafetorque[i]);
                        int number = Convert.ToInt32(partssafetorque[i]) - 30;
                        string hexStr = number.ToString("X");
                        newstringsafetorque += hexStr;
                    }
                }
                string resultstrsafetorque = newstringsafetorque;
                double doubleresultstrsafetorque = System.Convert.ToDouble(resultstrsafetorque) / 100;
                safetorques = doubleresultstrsafetorque;




                string anglethreshold = content.Substring(195, 24);
                string newstranglethreshold = anglethreshold.Substring(6, 18);
                string[] partsanglethreshold = newstranglethreshold.Split(' ');
                string newstringanglethreshold = "";
                List<string> listanglethreshold = new List<string>();
                for (int i = 0; i < partsanglethreshold.Length; i++)
                {
                    if (!string.IsNullOrEmpty(partsanglethreshold[i]))
                    {
                        listanglethreshold.Add(partsanglethreshold[i]);
                        int number = Convert.ToInt32(partsanglethreshold[i]) - 30;
                        string hexStr = number.ToString("X");
                        newstringanglethreshold += hexStr;
                    }
                }
                string resultstranglethreshold = newstringanglethreshold;
                double doubleresultstranglethreshold = System.Convert.ToDouble(resultstranglethreshold) / 100;
                anglethresholds = doubleresultstranglethreshold;




                string targettorque = content.Substring(219, 24);
                Debug.WriteLine("目标力矩------>"+ targettorque);
                string newstrtargettorque = targettorque.Substring(6, 18);
                string[] partstargettorque = newstrtargettorque.Split(' ');
                string newstringtargettorque = "";
                List<string> listtargettorque = new List<string>();
                for (int i = 0; i < partstargettorque.Length; i++)
                {
                    if (!string.IsNullOrEmpty(partstargettorque[i]))
                    {
                        listtargettorque.Add(partstargettorque[i]);
                        int number = Convert.ToInt32(partstargettorque[i]) - 30;
                        string hexStr = number.ToString("X");
                        newstringtargettorque += hexStr;
                    }
                }
                string resultstrtargettorque = newstringtargettorque;
                double doubleresultstrtargettorque = System.Convert.ToDouble(resultstrtargettorque) / 100;
                targettorques = doubleresultstrtargettorque;



                string Minangle = content.Substring(267, 24);
                string newstrMinangle = Minangle.Substring(6, 18);
                string[] partsMinangle = newstrMinangle.Split(' ');
                string newstringMinangle = "";
                List<string> listMinangle = new List<string>();
                for (int i = 0; i < partsMinangle.Length; i++)
                {
                    if (!string.IsNullOrEmpty(partsMinangle[i]))
                    {
                        listMinangle.Add(partsMinangle[i]);
                        int number = Convert.ToInt32(partsMinangle[i]) - 30;
                        string hexStr = number.ToString("X");
                        newstringMinangle += hexStr;
                    }
                }
                string resultstrMinangle = newstringMinangle;
                double doubleresultstrMinangle = System.Convert.ToDouble(resultstrMinangle) / 10;
                minangles = doubleresultstrMinangle;



                string Maxangle = content.Substring(291, 24);
                string newstrMaxangle = Maxangle.Substring(6, 18);
                string[] partsMaxangle = newstrMaxangle.Split(' ');
                string newstringMaxangle = "";
                List<string> listMaxangle = new List<string>();
                for (int i = 0; i < partsMaxangle.Length; i++)
                {
                    if (!string.IsNullOrEmpty(partsMaxangle[i]))
                    {
                        listMaxangle.Add(partsMaxangle[i]);
                        int number = Convert.ToInt32(partsMaxangle[i]) - 30;
                        string hexStr = number.ToString("X");
                        newstringMaxangle += hexStr;
                    }
                }
                string resultstrMaxangle = newstringMaxangle;
                double doubleresultstrMaxangle = System.Convert.ToDouble(resultstrMaxangle) / 10;
                maxangles = doubleresultstrMaxangle;




                string Safetyangle = content.Substring(315, 24);
                string newstrSafetyangle = Safetyangle.Substring(6, 18);
                string[] partsSafetyangle = newstrSafetyangle.Split(' ');
                string newstringSafetyangle = "";
                List<string> listSafetyangle = new List<string>();
                for (int i = 0; i < partsSafetyangle.Length; i++)
                {
                    if (!string.IsNullOrEmpty(partsSafetyangle[i]))
                    {
                        listSafetyangle.Add(partsSafetyangle[i]);
                        int number = Convert.ToInt32(partsSafetyangle[i]) - 30;
                        string hexStr = number.ToString("X");
                        newstringSafetyangle += hexStr;
                    }
                }
                string resultstrSafetyangle = newstringSafetyangle.Remove(0, 0);
                double doubleresultstrSafetyangle = System.Convert.ToDouble(resultstrSafetyangle) / 10;
                safeangles = doubleresultstrSafetyangle;




                string Targetangle = content.Substring(339, 24);
                Debug.WriteLine("目标角度------>"+ Targetangle);
                string newstrTargetangle = Targetangle.Substring(6, 18);
                string[] partsTargetangle = newstrTargetangle.Split(' ');
                string newstringTargetangle = "";
                List<string> listTargetangle = new List<string>();
                for (int i = 0; i < partsTargetangle.Length; i++)
                {
                    if (!string.IsNullOrEmpty(partsTargetangle[i]))
                    {
                        listTargetangle.Add(partsTargetangle[i]);
                        int number = Convert.ToInt32(partsTargetangle[i]) - 30;
                        string hexStr = number.ToString("X");
                        newstringTargetangle += hexStr;
                    }
                }
                string resultstrTargetangle = newstringTargetangle.Remove(0, 0);
                double doubleresultstrTargetangle = System.Convert.ToDouble(resultstrTargetangle) / 10;

                targetangles = doubleresultstrTargetangle;





                string Speed = content.Substring(483, 24);
                string newstrSpeed = Speed.Substring(6, 18);
                string[] partsSpeed = newstrSpeed.Split(' ');
                string newstringSpeed = "";
                List<string> listSpeed = new List<string>();
                for (int i = 0; i < partsSpeed.Length; i++)
                {
                    if (!string.IsNullOrEmpty(partsSpeed[i]))
                    {
                        listSpeed.Add(partsSpeed[i]);
                        int number = Convert.ToInt32(partsSpeed[i]) - 30;
                        string hexStr = number.ToString("X");
                        newstringSpeed += hexStr;
                    }
                }
                string resultstrSpeed = newstringSpeed;
                double doubleresultstrSpeed = System.Convert.ToDouble(resultstrSpeed);
                speeds = doubleresultstrSpeed;


                string taskid = content.Substring(72, 15);
                int taskidl = taskid.Length;
                string newstrtaskid = taskid.Substring(6, 9);
                string[] partstaskid = newstrtaskid.Split(' ');
                string newstringtaskid = "";
                List<string> listtaskid = new List<string>();
                for (int i = 0; i < partstaskid.Length; i++)
                {
                    if (!string.IsNullOrEmpty(partstaskid[i]))
                    {
                        listtaskid.Add(partstaskid[i]);
                        int number = Convert.ToInt32(partstaskid[i]) - 30;
                        string hexStr = number.ToString("X");
                        newstringtaskid += hexStr;
                    }
                }
                int resultstrtaskid = System.Convert.ToInt32(newstringtaskid); //newstringtaskid.Remove(0, 2);
                                                                               //任务存在则不添加
                DataTable dataTable = BLL.Bll.QueryContentWithTaskID("任务" + resultstrtaskid);
                if (dataTable.Rows.Count == 0)
                {
                    BLL.Bll.InsertParameterData("任务" + resultstrtaskid, resultstrtaskid.ToString(), "任务" + resultstrtaskid);
                }


                if (taskidlist.Count==0)
                {
                    taskidlist.Add("任务" + resultstrtaskid);
                }
                else
                {
                    if (taskidlist.Count > 0)
                    {
                        var checkresult = taskidlist.Where(x => x.Equals("任务" + resultstrtaskid)).ToList();
                        if (checkresult.Count == 0)
                        {
                            taskidlist.Add("任务" + resultstrtaskid);
                        }
                    }
                }

                //添加数据到DataTable
                //if (TaskDataTableData==null)
                //{
                //    TaskDataTableData = new DataTable();
                //    TaskDataTableData.Columns.Add("Content", typeof(string));
                //    taskidlist.Add("任务" + resultstrtaskid);
                //}
                //else
                //{

                //    if (taskidlist.Count>0)
                //    {
                //        var checkresult = taskidlist.Where(x=>x.Equals("任务" + resultstrtaskid)).ToList();
                //        if (checkresult.Count==0)
                //        {
                //            taskidlist.Add("任务" + resultstrtaskid);

                //            //DataRow newRow = dataTable.NewRow();

                //            //// 设置新行的各列值
                //            //newRow["Content"] = 1; // 假设这是一个整数

                //            //// 将新行添加到DataTable中
                //            //TaskDataTableData.Rows.Add(newRow);
                //        }
                //    }

                //}


                Debug.WriteLine("taskidlist->"+ taskidlist.Count);

                string stepid = content.Substring(87, 12);
                int stepidl = stepid.Length;
                string newstrstepid = stepid.Substring(6, 6);
                string[] partsstepid = newstrstepid.Split(' ');
                string newstringstepid = "";
                List<string> liststepid = new List<string>();
                for (int i = 0; i < partsstepid.Length; i++)
                {
                    if (!string.IsNullOrEmpty(partsstepid[i]))
                    {
                        liststepid.Add(partsstepid[i]);
                        int number = Convert.ToInt32(partsstepid[i]) - 30;
                        string hexStr = number.ToString("X");
                        newstringstepid += hexStr;
                    }
                }
                int resultstrstepid = System.Convert.ToInt32(newstringstepid); //newstringstepid.Remove(0, 2);


                string Steptype = content.Substring(99, 12);//4
                string newstrSteptype = Steptype.Substring(6, 2);
                byte bytesteptype = Convert.ToByte(newstrSteptype, 16);
                char[] SteptypecharArray = newstrSteptype.ToCharArray();
                string lengthsteptype = Convert.ToChar(bytesteptype).ToString();

                //if (lengthTighteningstrategytype == "1")
                //{
                //    //角度+扭矩
                //    tighteningType = "角度+扭矩";
                //}
                string tighteningType = "";
                //string tighteningTypes = "";
                switch (lengthTighteningstrategytype)
                {
                    case "0":
                        tighteningType = "扭矩";
                        //tighteningTypes = "扭矩优先";
                        break;
                    case "1":
                        tighteningType = "扭矩+角度";
                        //tighteningTypes = "扭矩优先";
                        break;
                    case "2":
                        tighteningType = "扭矩+角度+扭矩率";
                        //tighteningTypes = "扭矩优先";
                        break;
                    case "3":
                        tighteningType = "角度+扭矩";
                        //tighteningTypes = "角度优先";
                        break;
                    case "4":
                        tighteningType = "角度+扭矩+扭矩率";
                        //tighteningTypes = "角度优先";
                        break;
                    case "5":
                        tighteningType = "扭矩+电流";
                        //tighteningTypes = "角度优先";
                        break;
                    case "6":
                        tighteningType = "扭矩+角度+电流";
                        break;
                    case "?":
                        tighteningType = "无";
                        break;
                    default:
                        tighteningType = "无";
                        break;
                }
                DataTable speedmaxdt = BLL.Bll.GetBatchMaxSpeed();
                double factspeedmax = System.Convert.ToDouble(speedmaxdt.Rows[0][0].ToString());

                if (lengthsteptype == "S")
                {
                    //寻帽
                    stepnumberstype = "S";

                    string laps = (targetangles / 360).ToString();
                    DataTable dataTable1 = BLL.Bll.QueryTaskIdWithStepData(resultstrtaskid.ToString());
                    DataTable QueryStep = BLL.Bll.QueryStepByTaskIdWithStep(resultstrstepid.ToString(), resultstrtaskid.ToString());
                    //string newspeeds = (speeds*380).ToString();
                    double speedvalue = speeds / 100;
                    double factspeeds = speedvalue * factspeedmax;//圈数
                    if (QueryStep.Rows.Count == 0)
                    {


                        BLL.Bll.InsertStepData(resultstrtaskid.ToString(), resultstrstepid.ToString(), laps,
                                                factspeeds.ToString(), mintorques.ToString(), maxtorques.ToString(), safetorques.ToString(),
                                                anglethresholds.ToString(), targettorques.ToString(), minangles.ToString(), maxangles.ToString(),
                                                safeangles.ToString(), targetangles.ToString(), "寻帽", tighteningType);
                        // BLL.Bll.InsertStepData(resultstrtaskid.ToString(), resultstrstepid.ToString(), "0",
                        //factspeeds.ToString(), "0", "0", "0", "0", targettorques.ToString(), "0", "0", "0", "0", "寻帽", tighteningType);
                        //BLL.Bll.UpdateParameterData(resultstrtaskid, "任务" + resultstrtaskid + "(" + tighteningType + ")");
                        //BLL.Bll.InsertParameterData("任务" + resultstrtaskid + "(" + tighteningType + ")", resultstrtaskid.ToString());
                    }
                    else
                    {
                        //for (int j = 0; j < QueryStep.Rows.Count; j++)
                        //{
                        int id = Convert.ToInt32(QueryStep.Rows[0][0].ToString());


                        BLL.Bll.UpdateStepData(id, resultstrstepid.ToString(), laps, factspeeds.ToString(), mintorques.ToString(), maxtorques.ToString(), safetorques.ToString(), anglethresholds.ToString(), targettorques.ToString(), minangles.ToString(), maxangles.ToString(), safeangles.ToString(), targetangles.ToString());
                        //}
                    }

                    string newtaskstepstring = resultstrtaskid.ToString() + "," + resultstrstepid.ToString() + "," + laps + "," +
                      factspeeds.ToString() + "," + mintorques.ToString() + "," + maxtorques.ToString() + "," + safetorques.ToString() + "," +
                      anglethresholds.ToString() + "," + targettorques.ToString() + "," + minangles.ToString() + "," + maxangles.ToString() + "," +
                      safeangles.ToString() + "," + targetangles.ToString() + "," + "寻帽" + "," + tighteningType;
                    stepidlist.Add(newtaskstepstring);
                }

                if (lengthsteptype == "D")
                {
                    //快速下旋
                    stepnumberstype = "D";

                    string laps = (targetangles / 360).ToString();
                    DataTable dataTable1 = BLL.Bll.QueryTaskIdWithStepData(resultstrtaskid.ToString());
                    DataTable QueryStep = BLL.Bll.QueryStepByTaskIdWithStep(resultstrstepid.ToString(), resultstrtaskid.ToString());
                    //string newspeeds = (speeds*380).ToString();
                    double speedvalue = speeds / 100;
                    double factspeeds = speedvalue * factspeedmax;//圈数
                    if (QueryStep.Rows.Count == 0)
                    {
                        BLL.Bll.InsertStepData(resultstrtaskid.ToString(), resultstrstepid.ToString(), laps,
                             factspeeds.ToString(), mintorques.ToString(), maxtorques.ToString(), safetorques.ToString(),
                             anglethresholds.ToString(), targettorques.ToString(), minangles.ToString(), maxangles.ToString(),
                             safeangles.ToString(), targetangles.ToString(), "快速下旋", tighteningType);
                        //BLL.Bll.InsertStepData(resultstrtaskid.ToString(), resultstrstepid.ToString(), "0",
                        //speeds.ToString(), "0", "0", "0", "0", targettorques.ToString(), "0", "0", "0", "0", "快速下旋", tighteningType);
                        // BLL.Bll.InsertStepData(resultstrtaskid.ToString(), resultstrstepid.ToString(), "",
                        //factspeeds.ToString(), "", "", "", "", targettorques.ToString(), "", "", "", "", "快速下旋", tighteningType);
                        //BLL.Bll.UpdateParameterData(resultstrtaskid, "任务" + resultstrtaskid + "(" + tighteningType + ")");

                        //BLL.Bll.InsertParameterData("任务" + resultstrtaskid + "(" + tighteningType + ")", resultstrtaskid.ToString());
                    }
                    else
                    {
                        //for (int j = 0; j < QueryStep.Rows.Count; j++)
                        //{
                        int id = Convert.ToInt32(QueryStep.Rows[0][0].ToString());


                        BLL.Bll.UpdateStepData(id, resultstrstepid.ToString(), laps, factspeeds.ToString(), mintorques.ToString(), maxtorques.ToString(), safetorques.ToString(), anglethresholds.ToString(), targettorques.ToString(), minangles.ToString(), maxangles.ToString(), safeangles.ToString(), targetangles.ToString());
                        //}
                    }

                    string newtaskstepstring = resultstrtaskid.ToString()+","+ resultstrstepid.ToString() + "," + laps + "," +
                             factspeeds.ToString() + "," + mintorques.ToString() + "," + maxtorques.ToString() + "," + safetorques.ToString() + "," +
                             anglethresholds.ToString() + "," + targettorques.ToString() + "," + minangles.ToString() + "," + maxangles.ToString() + "," +
                             safeangles.ToString() + "," + targetangles.ToString() + "," + "快速下旋" + "," + tighteningType;
                    stepidlist.Add(newtaskstepstring);


                }

                if (lengthsteptype == "F")
                {
                    //最终拧紧
                    stepnumberstype = "F";
                    string laps = (targetangles / 360).ToString();
                    DataTable dataTable1 = BLL.Bll.QueryTaskIdWithStepData(resultstrtaskid.ToString());
                    DataTable QueryStep = BLL.Bll.QueryStepByTaskIdWithStep(resultstrstepid.ToString(), resultstrtaskid.ToString());
                    //DataTable speedmaxdt = BLL.Bll.GetBatchMaxSpeed();
                    //double factspeedmax =System.Convert.ToDouble(speedmaxdt.Rows[0][0].ToString());
                    double speedvalue = speeds / 100;
                    double factspeeds = speedvalue * factspeedmax;//圈数


                    if (QueryStep.Rows.Count == 0)
                    {
                        //BLL.Bll.InsertStepData(resultstrtaskid.ToString(), resultstrstepid.ToString(), laps,
                        //speeds.ToString(), mintorques.ToString(), maxtorques.ToString(), safetorques.ToString(),
                        //anglethresholds.ToString(), targettorques.ToString(), minangles.ToString(), maxangles.ToString(),
                        //safeangles.ToString(), targetangles.ToString(),"最终拧紧", tighteningType);

                        BLL.Bll.InsertStepData(resultstrtaskid.ToString(), resultstrstepid.ToString(), laps,
                                                factspeeds.ToString(), mintorques.ToString(), maxtorques.ToString(), safetorques.ToString(),
                                                anglethresholds.ToString(), targettorques.ToString(), minangles.ToString(), maxangles.ToString(),
                                                safeangles.ToString(), targetangles.ToString(), "最终拧紧", tighteningType);

                        //BLL.Bll.UpdateParameterData(resultstrtaskid, "任务" + resultstrtaskid+"("+ tighteningType + ")");
                        //BLL.Bll.InsertParameterData("任务" + resultstrtaskid + "(" + tighteningType + ")", resultstrtaskid.ToString());

                    }
                    else
                    {
                        //for (int j = 0; j < QueryStep.Rows.Count; j++)
                        //{
                        int id = Convert.ToInt32(QueryStep.Rows[0][0].ToString());

                        //BLL.Bll.UpdateStepData(id, resultstrstepid.ToString(), laps, speeds.ToString(), mintorques.ToString(),
                        //    maxtorques.ToString(), safetorques.ToString(), anglethresholds.ToString(), targettorques.ToString(),
                        //    minangles.ToString(), maxangles.ToString(), safeangles.ToString(), targetangles.ToString());

                        BLL.Bll.UpdateStepData(id, resultstrstepid.ToString(), laps, factspeeds.ToString(), mintorques.ToString(),
                        maxtorques.ToString(), safetorques.ToString(), anglethresholds.ToString(), targettorques.ToString(),
                        minangles.ToString(), maxangles.ToString(), safeangles.ToString(), targetangles.ToString());

                        //}
                    }
                    string newtaskstepstring = resultstrtaskid.ToString() + "," + resultstrstepid.ToString() + "," + laps + "," +
                             factspeeds.ToString() + "," + mintorques.ToString() + "," + maxtorques.ToString() + "," + safetorques.ToString() + "," +
                             anglethresholds.ToString() + "," + targettorques.ToString() + "," + minangles.ToString() + "," + maxangles.ToString() + "," +
                             safeangles.ToString() + "," + targetangles.ToString() + "," + "最终拧紧" + "," + tighteningType;
                    stepidlist.Add(newtaskstepstring);
                }

                if (lengthsteptype == "R")
                {
                    //反转
                    stepnumberstype = "R";

                    string laps = (targetangles / 360).ToString();
                    DataTable dataTable1 = BLL.Bll.QueryTaskIdWithStepData(resultstrtaskid.ToString());
                    DataTable QueryStep = BLL.Bll.QueryStepByTaskIdWithStep(resultstrstepid.ToString(), resultstrtaskid.ToString());
                    //string newspeeds = (speeds*380).ToString();
                    double speedvalue = speeds / 100;
                    double factspeeds = speedvalue * factspeedmax;//圈数
                    if (QueryStep.Rows.Count == 0)
                    {
                        BLL.Bll.InsertStepData(resultstrtaskid.ToString(), resultstrstepid.ToString(), laps,
             factspeeds.ToString(), mintorques.ToString(), maxtorques.ToString(), safetorques.ToString(),
             anglethresholds.ToString(), targettorques.ToString(), minangles.ToString(), maxangles.ToString(),
             safeangles.ToString(), targetangles.ToString(), "反转", tighteningType);
                        //BLL.Bll.InsertStepData(resultstrtaskid.ToString(), resultstrstepid.ToString(), "0",
                        //speeds.ToString(), "0", "0", "0", "0", targettorques.ToString(), "0", "0", "0", "0", "快速下旋", tighteningType);
                        // BLL.Bll.InsertStepData(resultstrtaskid.ToString(), resultstrstepid.ToString(), "0",
                        //factspeeds.ToString(), "0", "0", "0", "0", targettorques.ToString(), "0", "0", "0", "0", "反转", tighteningType);
                        //BLL.Bll.UpdateParameterData(resultstrtaskid, "任务" + resultstrtaskid + "(" + tighteningType + ")");

                        //BLL.Bll.InsertParameterData("任务" + resultstrtaskid + "(" + tighteningType + ")", resultstrtaskid.ToString());
                    }
                    else
                    {
                        //for (int j = 0; j < QueryStep.Rows.Count; j++)
                        //{
                        int id = Convert.ToInt32(QueryStep.Rows[0][0].ToString());

                        BLL.Bll.UpdateStepData(id, resultstrstepid.ToString(), laps, factspeeds.ToString(), mintorques.ToString(), maxtorques.ToString(), safetorques.ToString(), anglethresholds.ToString(), targettorques.ToString(), minangles.ToString(), maxangles.ToString(), safeangles.ToString(), targetangles.ToString());
                        //}
                    }
                    string newtaskstepstring = resultstrtaskid.ToString() + "," + resultstrstepid.ToString() + "," + laps + "," +
         factspeeds.ToString() + "," + mintorques.ToString() + "," + maxtorques.ToString() + "," + safetorques.ToString() + "," +
         anglethresholds.ToString() + "," + targettorques.ToString() + "," + minangles.ToString() + "," + maxangles.ToString() + "," +
         safeangles.ToString() + "," + targetangles.ToString() + "," + "反转" + "," + tighteningType;
                    stepidlist.Add(newtaskstepstring);
                }

                if (lengthsteptype == "V")
                {
                    //不合格动作
                    stepnumberstype = "V";

                    string laps = (targetangles / 360).ToString();
                    DataTable dataTable1 = BLL.Bll.QueryTaskIdWithStepData(resultstrtaskid.ToString());
                    DataTable QueryStep = BLL.Bll.QueryStepByTaskIdWithStep(resultstrstepid.ToString(), resultstrtaskid.ToString());
                    //string newspeeds = (speeds*380).ToString();
                    double speedvalue = speeds / 100;
                    double factspeeds = speedvalue * factspeedmax;//圈数
                    if (QueryStep.Rows.Count == 0)
                    {
                        BLL.Bll.InsertStepData(resultstrtaskid.ToString(), resultstrstepid.ToString(), laps,
factspeeds.ToString(), mintorques.ToString(), maxtorques.ToString(), safetorques.ToString(),
anglethresholds.ToString(), targettorques.ToString(), minangles.ToString(), maxangles.ToString(),
safeangles.ToString(), targetangles.ToString(), "不合格动作", tighteningType);
                        //BLL.Bll.InsertStepData(resultstrtaskid.ToString(), resultstrstepid.ToString(), "0",
                        //speeds.ToString(), "0", "0", "0", "0", targettorques.ToString(), "0", "0", "0", "0", "快速下旋", tighteningType);
                        // BLL.Bll.InsertStepData(resultstrtaskid.ToString(), resultstrstepid.ToString(), "0",
                        //factspeeds.ToString(), "0", "0", "0", "0", targettorques.ToString(), "0", "0", "0", "0", "不合格动作", tighteningType);
                        //BLL.Bll.UpdateParameterData(resultstrtaskid, "任务" + resultstrtaskid + "(" + tighteningType + ")");

                        //BLL.Bll.InsertParameterData("任务" + resultstrtaskid + "(" + tighteningType + ")", resultstrtaskid.ToString());
                    }
                    else
                    {
                        //for (int j = 0; j < QueryStep.Rows.Count; j++)
                        //{
                        int id = Convert.ToInt32(QueryStep.Rows[0][0].ToString());


                        BLL.Bll.UpdateStepData(id, resultstrstepid.ToString(), laps, factspeeds.ToString(), mintorques.ToString(), maxtorques.ToString(), safetorques.ToString(), anglethresholds.ToString(), targettorques.ToString(), minangles.ToString(), maxangles.ToString(), safeangles.ToString(), targetangles.ToString());
                        //}
                    }
                    string newtaskstepstring = resultstrtaskid.ToString() + "," + resultstrstepid.ToString() + "," + laps + "," +
         factspeeds.ToString() + "," + mintorques.ToString() + "," + maxtorques.ToString() + "," + safetorques.ToString() + "," +
         anglethresholds.ToString() + "," + targettorques.ToString() + "," + minangles.ToString() + "," + maxangles.ToString() + "," +
         safeangles.ToString() + "," + targetangles.ToString() + "," + "不合格动作" + "," + tighteningType;
                    stepidlist.Add(newtaskstepstring);
                }

                if (lengthsteptype == "J")
                {
                    //跳转
                    stepnumberstype = "J";

                    string laps = (targetangles / 360).ToString();
                    DataTable dataTable1 = BLL.Bll.QueryTaskIdWithStepData(resultstrtaskid.ToString());
                    DataTable QueryStep = BLL.Bll.QueryStepByTaskIdWithStep(resultstrstepid.ToString(), resultstrtaskid.ToString());
                    //string newspeeds = (speeds*380).ToString();
                    double speedvalue = speeds / 100;
                    double factspeeds = speedvalue * factspeedmax;//圈数
                    if (QueryStep.Rows.Count == 0)
                    {

                        BLL.Bll.InsertStepData(resultstrtaskid.ToString(), resultstrstepid.ToString(), laps,
factspeeds.ToString(), mintorques.ToString(), maxtorques.ToString(), safetorques.ToString(),
anglethresholds.ToString(), targettorques.ToString(), minangles.ToString(), maxangles.ToString(),
safeangles.ToString(), targetangles.ToString(), "跳转", tighteningType);

                        //BLL.Bll.InsertStepData(resultstrtaskid.ToString(), resultstrstepid.ToString(), "0",
                        //speeds.ToString(), "0", "0", "0", "0", targettorques.ToString(), "0", "0", "0", "0", "快速下旋", tighteningType);
                        // BLL.Bll.InsertStepData(resultstrtaskid.ToString(), resultstrstepid.ToString(), "0",
                        //factspeeds.ToString(), "0", "0", "0", "0", targettorques.ToString(), "0", "0", "0", "0", "跳转", tighteningType);
                        //BLL.Bll.UpdateParameterData(resultstrtaskid, "任务" + resultstrtaskid + "(" + tighteningType + ")");

                        //BLL.Bll.InsertParameterData("任务" + resultstrtaskid + "(" + tighteningType + ")", resultstrtaskid.ToString());
                    }
                    else
                    {
                        //for (int j = 0; j < QueryStep.Rows.Count; j++)
                        //{
                        int id = Convert.ToInt32(QueryStep.Rows[0][0].ToString());


                        BLL.Bll.UpdateStepData(id, resultstrstepid.ToString(), laps, factspeeds.ToString(), mintorques.ToString(), maxtorques.ToString(), safetorques.ToString(), anglethresholds.ToString(), targettorques.ToString(), minangles.ToString(), maxangles.ToString(), safeangles.ToString(), targetangles.ToString());
                        //}
                    }
                    string newtaskstepstring = resultstrtaskid.ToString() + "," + resultstrstepid.ToString() + "," + laps + "," +
         factspeeds.ToString() + "," + mintorques.ToString() + "," + maxtorques.ToString() + "," + safetorques.ToString() + "," +
         anglethresholds.ToString() + "," + targettorques.ToString() + "," + minangles.ToString() + "," + maxangles.ToString() + "," +
         safeangles.ToString() + "," + targetangles.ToString() + "," + "跳转" + "," + tighteningType;
                    stepidlist.Add(newtaskstepstring);
                }

                if (lengthsteptype == "T")
                {
                    //跳转
                    stepnumberstype = "T";

                    string laps = (targetangles / 360).ToString();
                    DataTable dataTable1 = BLL.Bll.QueryTaskIdWithStepData(resultstrtaskid.ToString());
                    DataTable QueryStep = BLL.Bll.QueryStepByTaskIdWithStep(resultstrstepid.ToString(), resultstrtaskid.ToString());
                    //string newspeeds = (speeds*380).ToString();
                    double speedvalue = speeds / 100;
                    double factspeeds = speedvalue * factspeedmax;//圈数
                    if (QueryStep.Rows.Count == 0)
                    {

                        BLL.Bll.InsertStepData(resultstrtaskid.ToString(), resultstrstepid.ToString(), laps,
factspeeds.ToString(), mintorques.ToString(), maxtorques.ToString(), safetorques.ToString(),
anglethresholds.ToString(), targettorques.ToString(), minangles.ToString(), maxangles.ToString(),
safeangles.ToString(), targetangles.ToString(), "摩檫力扭矩监控", tighteningType);

                        //BLL.Bll.InsertStepData(resultstrtaskid.ToString(), resultstrstepid.ToString(), "0",
                        //speeds.ToString(), "0", "0", "0", "0", targettorques.ToString(), "0", "0", "0", "0", "快速下旋", tighteningType);
                        // BLL.Bll.InsertStepData(resultstrtaskid.ToString(), resultstrstepid.ToString(), "0",
                        //factspeeds.ToString(), "0", "0", "0", "0", targettorques.ToString(), "0", "0", "0", "0", "摩檫力扭矩监控", tighteningType);
                        //BLL.Bll.UpdateParameterData(resultstrtaskid, "任务" + resultstrtaskid + "(" + tighteningType + ")");

                        //BLL.Bll.InsertParameterData("任务" + resultstrtaskid + "(" + tighteningType + ")", resultstrtaskid.ToString());
                    }
                    else
                    {
                        //for (int j = 0; j < QueryStep.Rows.Count; j++)
                        //{
                        int id = Convert.ToInt32(QueryStep.Rows[0][0].ToString());


                        BLL.Bll.UpdateStepData(id, resultstrstepid.ToString(), laps, factspeeds.ToString(), mintorques.ToString(), maxtorques.ToString(), safetorques.ToString(), anglethresholds.ToString(), targettorques.ToString(), minangles.ToString(), maxangles.ToString(), safeangles.ToString(), targetangles.ToString());
                        //}
                    }
                    string newtaskstepstring = resultstrtaskid.ToString() + "," + resultstrstepid.ToString() + "," + laps + "," +
         factspeeds.ToString() + "," + mintorques.ToString() + "," + maxtorques.ToString() + "," + safetorques.ToString() + "," +
         anglethresholds.ToString() + "," + targettorques.ToString() + "," + minangles.ToString() + "," + maxangles.ToString() + "," +
         safeangles.ToString() + "," + targetangles.ToString() + "," + "摩檫力扭矩监控" + "," + tighteningType;
                    stepidlist.Add(newtaskstepstring);
                }

                if (lengthsteptype == "W")
                {
                    //跳转
                    stepnumberstype = "W";

                    string laps = (targetangles / 360).ToString();
                    DataTable dataTable1 = BLL.Bll.QueryTaskIdWithStepData(resultstrtaskid.ToString());
                    DataTable QueryStep = BLL.Bll.QueryStepByTaskIdWithStep(resultstrstepid.ToString(), resultstrtaskid.ToString());
                    //string newspeeds = (speeds*380).ToString();
                    double speedvalue = speeds / 100;
                    double factspeeds = speedvalue * factspeedmax;//圈数
                    if (QueryStep.Rows.Count == 0)
                    {
                        BLL.Bll.InsertStepData(resultstrtaskid.ToString(), resultstrstepid.ToString(), laps,
factspeeds.ToString(), mintorques.ToString(), maxtorques.ToString(), safetorques.ToString(),
anglethresholds.ToString(), targettorques.ToString(), minangles.ToString(), maxangles.ToString(),
safeangles.ToString(), targetangles.ToString(), "等待同步", tighteningType);
                        //BLL.Bll.InsertStepData(resultstrtaskid.ToString(), resultstrstepid.ToString(), "0",
                        //speeds.ToString(), "0", "0", "0", "0", targettorques.ToString(), "0", "0", "0", "0", "快速下旋", tighteningType);
                        // BLL.Bll.InsertStepData(resultstrtaskid.ToString(), resultstrstepid.ToString(), "0",
                        //factspeeds.ToString(), "0", "0", "0", "0", targettorques.ToString(), "0", "0", "0", "0", "等待同步", tighteningType);
                        //BLL.Bll.UpdateParameterData(resultstrtaskid, "任务" + resultstrtaskid + "(" + tighteningType + ")");

                        //BLL.Bll.InsertParameterData("任务" + resultstrtaskid + "(" + tighteningType + ")", resultstrtaskid.ToString());
                    }
                    else
                    {
                        //for (int j = 0; j < QueryStep.Rows.Count; j++)
                        //{
                        int id = Convert.ToInt32(QueryStep.Rows[0][0].ToString());


                        BLL.Bll.UpdateStepData(id, resultstrstepid.ToString(), laps, factspeeds.ToString(), mintorques.ToString(), maxtorques.ToString(), safetorques.ToString(), anglethresholds.ToString(), targettorques.ToString(), minangles.ToString(), maxangles.ToString(), safeangles.ToString(), targetangles.ToString());
                        //}
                    }
                    string newtaskstepstring = resultstrtaskid.ToString() + "," + resultstrstepid.ToString() + "," + laps + "," +
         factspeeds.ToString() + "," + mintorques.ToString() + "," + maxtorques.ToString() + "," + safetorques.ToString() + "," +
         anglethresholds.ToString() + "," + targettorques.ToString() + "," + minangles.ToString() + "," + maxangles.ToString() + "," +
         safeangles.ToString() + "," + targetangles.ToString() + "," + "等待同步" + "," + tighteningType;
                    stepidlist.Add(newtaskstepstring);
                }

                if (lengthsteptype == "d")
                {
                    //跳转
                    stepnumberstype = "d";

                    string laps = (targetangles / 360).ToString();
                    DataTable dataTable1 = BLL.Bll.QueryTaskIdWithStepData(resultstrtaskid.ToString());
                    DataTable QueryStep = BLL.Bll.QueryStepByTaskIdWithStep(resultstrstepid.ToString(), resultstrtaskid.ToString());
                    //string newspeeds = (speeds*380).ToString();
                    double speedvalue = speeds / 100;
                    double factspeeds = speedvalue * factspeedmax;//圈数
                    if (QueryStep.Rows.Count == 0)
                    {

                        BLL.Bll.InsertStepData(resultstrtaskid.ToString(), resultstrstepid.ToString(), laps,
factspeeds.ToString(), mintorques.ToString(), maxtorques.ToString(), safetorques.ToString(),
anglethresholds.ToString(), targettorques.ToString(), minangles.ToString(), maxangles.ToString(),
safeangles.ToString(), targetangles.ToString(), "角度控制快速下旋", tighteningType);

                        //BLL.Bll.InsertStepData(resultstrtaskid.ToString(), resultstrstepid.ToString(), "0",
                        //speeds.ToString(), "0", "0", "0", "0", targettorques.ToString(), "0", "0", "0", "0", "快速下旋", tighteningType);
                        // BLL.Bll.InsertStepData(resultstrtaskid.ToString(), resultstrstepid.ToString(), "0",
                        //factspeeds.ToString(), "0", "0", "0", "0", targettorques.ToString(), "0", "0", "0", "0", "角度控制快速下旋", tighteningType);
                        //BLL.Bll.UpdateParameterData(resultstrtaskid, "任务" + resultstrtaskid + "(" + tighteningType + ")");

                        //BLL.Bll.InsertParameterData("任务" + resultstrtaskid + "(" + tighteningType + ")", resultstrtaskid.ToString());
                    }
                    else
                    {
                        //for (int j = 0; j < QueryStep.Rows.Count; j++)
                        //{
                        int id = Convert.ToInt32(QueryStep.Rows[0][0].ToString());


                        BLL.Bll.UpdateStepData(id, resultstrstepid.ToString(), laps, factspeeds.ToString(), mintorques.ToString(), maxtorques.ToString(), safetorques.ToString(), anglethresholds.ToString(), targettorques.ToString(), minangles.ToString(), maxangles.ToString(), safeangles.ToString(), targetangles.ToString());
                        //}
                    }
                    string newtaskstepstring = resultstrtaskid.ToString() + "," + resultstrstepid.ToString() + "," + laps + "," +
         factspeeds.ToString() + "," + mintorques.ToString() + "," + maxtorques.ToString() + "," + safetorques.ToString() + "," +
         anglethresholds.ToString() + "," + targettorques.ToString() + "," + minangles.ToString() + "," + maxangles.ToString() + "," +
         safeangles.ToString() + "," + targetangles.ToString() + "," + "角度控制快速下旋" + "," + tighteningType;
                    stepidlist.Add(newtaskstepstring);
                }



                for (int i = 0; i < stepidlist.Count; i++)
                {
                    Debug.WriteLine("stepidlist->"+"序号："+ i+"内容->"+ stepidlist[i]);
                }
   

                //                //程序号
                //public static int psetnumbers;
                ////步骤号
                //public static int stepnumbers;

                //public static string stepnumberstype;

                ////最小扭矩
                //public static double mintorques;
                //public static double maxtorques;
                //public static double safetorques;
                //public static double targettorques;
                //public static double anglethresholds;
                //public static double minangles;
                //public static double maxangles;
                //public static double safeangles;
                //public static double targetangles;
                //public static double speeds;
            }

            //if (content.Contains(""))
            //{
            //    //连接状态
            //}
            //错误码00260004
            if (content.Contains("30 30 32 36 30 30 30 34"))
            {
                //执行状态
                ExecuteState = "执行失败";
            }
        }

        /// <summary>
        /// 心跳发送
        /// </summary>
        public static void AutoSend()
        {
            try
            {
                if (isMonitor)
                {
                    //if(thread!=null)
                    //{
                    //    thread.Abort();
                    //}
                    //创建线程
                    thread = new Thread(CircularTransmission);

                    thread.Start();//启动线程

                    //jytAutoSend.Text = "停止发送";
                }
                else
                {
                    ConnectionState = "错误" + "心跳未发送";
                    Debug.WriteLine("ConnectionState->" + ConnectionState);
                    thread.Abort();
                    //jytAutoSend.Text = "循环发送";
                    //MessageBox.Show("监听未打开", "错误");
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("AutoSend->" + ex.Message);
            }

        }

        private static void CircularTransmission()
        {
                //判断是否是连接状态
                if (isMonitor)
                {
                    
                    // 死循环 发送右侧 jytCMD 控件勾选了的 数据
                    while (true)
                    {
                        try
                        {
                            //发送一条 等待 设置的间隔事件 单位毫秒
                            Thread.Sleep(5000);//Thread.Sleep(int.Parse(jytDelay.Value.ToString()));
                            byte[] _jytbyte = Transformation("30 30 32 30 39 39 39 39 20 20 20 20 20 20 20 20 20 20 20 20 00");
                            tcpclient.GetStream().Write(_jytbyte, 0, _jytbyte.Length);//发送内容
                        }
                        catch (Exception ex)
                        {

                            Debug.WriteLine("ConnectionState之前->" + ConnectionState);
                            Reconnect();
                            //MessageBox.Show("发送失败", "错误");
                            Debug.WriteLine("ConnectionState之后->" + ConnectionState);

                            ConnectionState = "错误" + ex.Message.ToString();
                            Debug.WriteLine("ConnectionState->" + ConnectionState);
                        }

                    }
                }
                else
                {
                    thread.Abort();
                    //jytAutoSend.Text = "循环发送";
                }

        }

        //处理发送数据 时 将内容转换为 选择jytCodingtype的编码格式数据
        private static byte[] Transformation(string textdata)
        {
            byte[] data = null;

            string[] HexStr = textdata.Trim().Split(' ');
            data = new byte[HexStr.Length];
            for (int i = 0; i < HexStr.Length; i++)
            {
                data[i] = (byte)(Convert.ToInt32(HexStr[i], 16));
            }
            return data;
        }

        //发送单条
        //不知道为啥 单独写了一个这个 忘了 其实 单独写这个方法
        //直接在 调用处 调用SendData就可以 懒得改了
        public static void SendOut(string data)
        {
            try
            {

                if (tcpclient==null)
                {
                    return;
                }
                byte[] _jytbyte = Transformation(data); //System.Text.Encoding.Default.GetBytes(data);

                tcpclient.GetStream().Write(_jytbyte, 0, _jytbyte.Length);
            }
            catch (Exception ex)
            {
                ConnectionState = "错误" + ex.Message.ToString();
                Reconnect();
            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="psetnumber">任务号</param>
        /// <param name="stepnumber">步骤号</param>
        /// <param name="mintorque"></param>
        /// <param name="maxtorque"></param>
        /// <param name="safetorque"></param>
        /// <param name="targettorque"></param>
        /// <param name="minangle"></param>
        /// <param name="maxangle"></param>
        /// <param name="safeangle"></param>
        /// <param name="targetangle"></param>
        /// <param name="speed"></param>
        public static void ExecuteChangeData(int psetnumber, int stepnumber, double mintorque, double maxtorque, double safetorque, double anglethreshold, double targettorque, double minangle, double maxangle, double safeangle, double targetangle, double speed)
        {
            //角度阈值 09
            string strmintorque = "30 36 " + GetMinTorqueLength(mintorque);
            string strmaxtorque = "30 37 " + GetMaxTorqueLength(maxtorque);
            string strsafetorque = "30 38 " + GetSafeTorqueLength(safetorque);
            string stranglethreshold = "30 39 " + GetAnglethreshold(anglethreshold);
            string strtargettorque = "31 30 " + GetTargetTorqueLength(targettorque);
            string strminangle = "31 32 " + GetMinAngle(minangle);
            string strmaxangle = "31 33 " + GetMaxAngle(maxangle);
            string strsafeangle = "31 34 " + GetSafeAngle(safeangle);
            string strtargetangle = "31 35 " + GetTargetAngle(targetangle);
            string strspeed = "32 31 " + GetSpeed(speed);
            string result = AnalyseData(psetnumber, stepnumber, strmintorque, strmaxtorque, strsafetorque, stranglethreshold, strtargettorque, strminangle, strmaxangle, strsafeangle, strtargetangle, strspeed);
            SendOut(result);
            Debug.WriteLine("ExecuteChangeData--->" + result);

            //程序号
            psetnumbers = psetnumber;

            //最小扭矩
            mintorques = mintorque;

            maxtorques = maxtorque;
            safetorques = safetorque;
            targettorques = targettorque;
            minangles = minangle;
            maxangles = maxangle;
            safeangles = safeangle;
            targetangles = targetangle;
            speeds = speed;

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="Psetnumber">程序号</param>
        /// <param name="MinTorqueLength"></param>
        /// <param name="MaxTorqueLength"></param>
        /// <param name="SafeTorqueLength"></param>
        /// <param name="TargetTorqueLength"></param>
        /// <param name="MinAngle"></param>
        /// <param name="MaxAngle"></param>
        /// <param name="SafeAngle"></param>
        /// <param name="TargetAngle"></param>
        /// <param name="Speed"></param>
        /// <returns></returns>
        public static string AnalyseData(int Psetnumber, int stepnumber, string MinTorqueLength, string MaxTorqueLength, string SafeTorqueLength, string Anglethreshold, string TargetTorqueLength, string MinAngle, string MaxAngle, string SafeAngle, string TargetAngle, string Speed)
        {
            //任务
            string newstring = Psetnumber.ToString().PadLeft(3, '0');

            string hexstring = ConvertStringToHex(newstring);

            var results = InsertFormat(hexstring, 2, " ") + " ";


            //步骤
            string newstepstring = stepnumber.ToString().PadLeft(2, '0');

            string hexstepstring = ConvertStringToHex(newstepstring);

            var stepresults = InsertFormat(hexstepstring, 2, " ") + " ";

            string result = "";

            #region

            //30 32 35 36 37 34 31 34 30 30 31
            //20 20 20 20 20 20 20 20 20
            //30 31 30 31 30 32 30 30 31 
            //30 33 30 32 
            //30 34 46 20
            //30 35 31 20
            //30 36 30 30 30 33 30 30
            //30 37 30 30 30 38 30 30
            //30 38 30 30 30 30 30 30
            //30 39 30 30 30 33 35 30
            //31 30 30 30 30 37 30 30
            //31 31 20 20 20 20 20 20
            //31 32 30 30 30 30 30 30
            //31 33 30 39 39 39 39 30
            //31 34 39 39 39 39 39 30
            //31 35 30 30 30 30 30 30
            //31 36 20 20 20 20 20 20
            //31 37 20 20 20 20 20 20
            //31 38 20 20 20 20 20 20
            //31 39 30 30 30 31 30 30
            //32 30 20 20 20 20 20 20
            //32 31 30 30 30 30 39 33
            //32 32 30 30 30 30 30 30
            //32 33 30 30 30 30 30 30
            //32 34 30 30
            //32 35 30 30 30 30 30 30
            //32 36 30 30 30 30 30 30
            //32 37 30 30 30 30
            //32 38 30 30 30 30
            //32 39 20 20 20 20 20 20
            //33 30 20 20 20 20 20 20
            //33 31 20 20 20 20 20 20
            //33 32 43 57
            //33 33 54
            //33 34 30 30 30
            //33 35 30 00

            #endregion

            string header = "30 32 35 36 37 34 31 34 30 30 31 ";
            string space = "20 20 20 20 20 20 20 20 20 ";//空格
            string one = "30 31 30 31 ";
            //string two = "30 32 30 30 31 ";//程序号
            string two = "30 32 ";//程序号
            string three = results; //"30 30 32";
            string stepnumbers = "30 33 ";//步骤号
            string strstepnumber = stepresults;
            string fournumber = "30 34 46 20 ";
            string fivenumber = "30 35 31 20 ";
            string sixnumber = "30 36 30 30 30 33 30 30 ";//最小扭矩
            string senvernumber = "30 37 30 30 30 38 30 30 ";//最大扭矩
            string eightnumber = "30 38 30 30 30 30 30 30 ";//安全力矩
            string ninenumber = "30 39 30 30 30 33 35 30 ";
            string tennumber = "31 30 30 30 30 37 30 30 ";//目标力矩
            string eleven = "31 31 20 20 20 20 20 20 ";
            string twelve = "31 32 30 30 30 30 30 30 ";//最小角度
            string thirteen = "31 33 30 39 39 39 39 30 ";//最大角度
            string fourteen = "31 34 39 39 39 39 39 30 ";//安全角度
            string fiveteen = "31 35 30 30 30 30 30 30 ";//目标角度
            string sixteen = "31 36 20 20 20 20 20 20 ";
            string seventeen = "31 37 20 20 20 20 20 20 ";
            string eighteen = "31 38 20 20 20 20 20 20 ";
            string nineteen = "31 39 30 30 30 31 30 30 ";
            string twenty = "32 30 20 20 20 20 20 20 ";
            string twentyone = "32 31 30 30 30 30 39 33 ";//速度
            string twentytwo = "32 32 30 30 30 30 30 30 ";
            string twentythree = "32 33 30 30 30 30 30 30 ";
            string twentyfour = "32 34 30 30 ";
            string twentyfive = "32 35 30 30 30 30 30 30 ";
            string twentysix = "32 36 30 30 30 30 30 30 ";
            string twentyseven = "32 37 30 30 30 30 ";
            string twentyeight = "32 38 30 30 30 30 ";
            string thirty = "32 39 20 20 20 20 20 20 ";
            string thirtyone = "33 30 20 20 20 20 20 20 ";
            string thirtytwo = "33 31 20 20 20 20 20 20 ";
            string thirtythree = "33 32 43 57 ";
            string thirtyfour = "33 33 54 ";
            string thirtyfive = "33 34 30 30 30 ";
            string thirtysix = "33 35 30 00";

            if (!string.IsNullOrEmpty(MinTorqueLength))
            {
                sixnumber = MinTorqueLength;
            }

            if (!string.IsNullOrEmpty(MaxTorqueLength))
            {
                senvernumber = MaxTorqueLength;
            }

            if (!string.IsNullOrEmpty(SafeTorqueLength))
            {
                eightnumber = SafeTorqueLength;
            }

            if (!string.IsNullOrEmpty(Anglethreshold))
            {
                ninenumber = Anglethreshold;
            }

            if (!string.IsNullOrEmpty(TargetTorqueLength))
            {
                tennumber = TargetTorqueLength;
            }


            if (!string.IsNullOrEmpty(MinAngle))
            {
                twelve = MinAngle;
            }

            if (!string.IsNullOrEmpty(MaxAngle))
            {
                thirteen = MaxAngle;
            }

            if (!string.IsNullOrEmpty(SafeAngle))
            {
                fourteen = SafeAngle;
            }

            if (!string.IsNullOrEmpty(TargetAngle))
            {
                fiveteen = TargetAngle;
            }

            if (!string.IsNullOrEmpty(Speed))
            {
                twentyone = Speed;
            }

            string befor = header + space + one + two + three + stepnumbers + strstepnumber + fournumber + fivenumber;
            string mid = sixnumber + senvernumber + eightnumber + ninenumber + tennumber + eleven + twelve + thirteen + fourteen + fiveteen;//修改的数据
            string mids = sixteen + seventeen + eighteen + nineteen + twenty;
            string midafter = twentyone;//修改的数据
            string after = twentytwo + twentythree + twentyfour + twentyfive + twentysix + twentyseven + twentyeight + thirty + thirtyone + thirtytwo + thirtythree + thirtyfour + thirtyfive + thirtysix;

            result = befor + mid + mids + midafter + after;

            return result;
        }

        //最小扭矩
        public static string GetMinTorqueLength(double data)
        {
            string result = "";

            double newvalue = data * 100;

            string newstring = newvalue.ToString().PadLeft(6, '0');

            string hexstring = ConvertStringToHex(newstring);

            result = InsertFormat(hexstring, 2, " ") + " ";

            //var newresult = " ";

            return result;

        }

        //最大扭矩
        public static string GetMaxTorqueLength(double data)
        {
            string result = "";

            double newvalue = data * 100;

            string newstring = newvalue.ToString().PadLeft(6, '0');

            string hexstring = ConvertStringToHex(newstring);

            result = InsertFormat(hexstring, 2, " ") + " ";

            //var newresult = " ";

            return result;
        }

        //安全力矩
        public static string GetSafeTorqueLength(double data)
        {
            string result = "";

            double newvalue = data * 100;

            string newstring = newvalue.ToString().PadLeft(6, '0');

            string hexstring = ConvertStringToHex(newstring);

            result = InsertFormat(hexstring, 2, " ") + " ";

            //var newresult = " ";

            return result;
        }

        //角度阈值
        public static string GetAnglethreshold(double data)
        {
            string result = "";

            double newvalue = data * 100;

            string newstring = newvalue.ToString().PadLeft(6, '0');

            string hexstring = ConvertStringToHex(newstring);

            result = InsertFormat(hexstring, 2, " ") + " ";

            //var newresult = " ";

            return result;
        }

        //目标力矩
        public static string GetTargetTorqueLength(double data)
        {
            string result = "";

            double newvalue = data * 100;

            string newstring = newvalue.ToString().PadLeft(6, '0');

            string hexstring = ConvertStringToHex(newstring);

            result = InsertFormat(hexstring, 2, " ") + " ";

            //var newresult = " ";

            return result;
        }

        //最小角度
        public static string GetMinAngle(double data)
        {
            string result = "";

            double newvalue = data * 10;

            string newstring = newvalue.ToString().PadLeft(6, '0');

            string hexstring = ConvertStringToHex(newstring);

            result = InsertFormat(hexstring, 2, " ") + " ";

            //var newresult = " ";

            return result;
        }

        //最大角度
        public static string GetMaxAngle(double data)
        {
            string result = "";

            double newvalue = data * 10;

            string newstring = newvalue.ToString().PadLeft(6, '0');

            string hexstring = ConvertStringToHex(newstring);

            result = InsertFormat(hexstring, 2, " ") + " ";

            //var newresult = " ";

            return result;
        }
        //安全角度
        public static string GetSafeAngle(double data)
        {
            string result = "";

            double newvalue = data * 10;

            string newstring = newvalue.ToString().PadLeft(6, '0');

            string hexstring = ConvertStringToHex(newstring);

            result = InsertFormat(hexstring, 2, " ") + " ";

            //var newresult = " ";

            return result;
        }

        //目标角度
        public static string GetTargetAngle(double data)
        {
            string result = "";

            double newvalue = data * 10;

            string newstring = newvalue.ToString().PadLeft(6, '0');

            string hexstring = ConvertStringToHex(newstring);

            result = InsertFormat(hexstring, 2, " ") + " ";

            //var newresult = " ";

            return result;
        }

        //速度
        public static string GetSpeed(double data)
        {
            string result = "";

            double newvalue = data;

            string newstring = newvalue.ToString().PadLeft(6, '0');

            string hexstring = ConvertStringToHex(newstring);

            result = InsertFormat(hexstring, 2, " ") + " ";

            //var newresult = " ";

            return result;
        }

        /// <summary>
        /// 步骤订阅(00207402)
        /// PHASES RESULTS SUBSCRIBE
        /// </summary>
        public static void SetPhasesSubscribe()
        {
            SendOut("30 30 32 30 37 34 30 32 20 20 20 20 20 20 20 20 20 20 20 20 00");
        }

        /// <summary>
        /// 曲线订阅(00207408001)
        /// LAST CURVE SUBSCRIBE
        /// </summary>
        public static void SetLastCurve()
        {
            SendOut("30 30 32 30 37 34 30 38 20 20 20 20 20 20 20 20 20 20 20 20 00");
        }

        /// <summary>
        /// 转成16进制
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string ConvertStringToHex(string input)
        {
            byte[] byteArray = Encoding.UTF8.GetBytes(input);
            string hexString = BitConverter.ToString(byteArray);
            return hexString.Replace("-", "");
        }

        /// <summary>
        /// 间隔N个字符插入字符
        /// </summary>
        /// <param name="input">输入字符</param>
        /// <param name="interval">几个间隔数</param>
        /// <param name="value">插入符号</param>
        /// <returns></returns>
        public static string InsertFormat(string input, int interval, string value)
        {
            for (int i = interval; i < input.Length; i += interval + 1)
            {
                input = input.Insert(i, value);
            }
            return input;
        }

        /// <summary>
        /// 握手
        /// </summary>
        public static void GetHand()
        {
            SendOut("30 30 32 30 30 30 30 31 20 20 20 20 20 20 20 20 20 20 20 20 00");//握手
        }

        /// <summary>
        /// 使能
        /// </summary>
        public static void Enable()
        {
            SendOut("30 30 32 30 30 30 34 33 20 20 20 20 20 20 20 20 20 20 20 20 00");//使能
        }

        /// <summary>
        /// 不使能
        /// </summary>
        public static void DisEnable()
        {
            SendOut("30 30 32 30 30 30 34 32 20 20 20 20 20 20 20 20 20 20 20 20 00");//不使能
        }

        /// <summary>
        /// 订阅结果
        /// </summary>
        public static void SetResult()
        {
            SendOut("30 30 32 30 30 30 36 30 20 20 20 20 20 20 20 20 20 20 20 20 00");//订阅结果
        }

        ///// <summary>
        ///// 步骤订阅(00207402)
        ///// PHASES RESULTS SUBSCRIBE
        ///// </summary>
        //public static void SetPhasesSubscribe()
        //{
        //    Common.Batch.SendOut("30 30 32 30 37 34 30 32 20 20 20 20 20 20 20 20 20 20 20 20 00");
        //}

        ///// <summary>
        ///// 曲线订阅(00207408001)
        ///// LAST CURVE SUBSCRIBE
        ///// </summary>
        //public static void SetLastCurve()
        //{
        //    Common.Batch.SendOut("30 30 32 30 37 34 30 38 20 20 20 20 20 20 20 20 20 20 20 20 00");
        //}

        /// <summary>
        /// 读取程序参数
        /// </summary>
        /// <param name="tasknumber">任务号</param>
        /// <param name="stepnumber">程序号</param>
        public static void GetParameter(int tasknumber, int stepnumber)
        {
            //任务号转为16进制字符串
            string strtasknumber = tasknumber.ToString().PadLeft(3, '0');

            string tasknumberhexstring = ConvertStringToHex(strtasknumber);

            string tasknumberresult = InsertFormat(tasknumberhexstring, 2, " ") + "";

            //步骤号转为16进制字符串
            string strstepnumber = stepnumber.ToString().PadLeft(2, '0');

            string stepnumberhexstring = ConvertStringToHex(strstepnumber);

            string stepnumberresult = InsertFormat(stepnumberhexstring, 2, " ") + "";

            SendOut("30 30 32 39 37 34 31 32 30 30 31 20 20 20 20 20 20 20 20 20 30 31 " + tasknumber + " 30 32 " + stepnumber + " 00");//读取程序参数
        }

        public static void NewGetParameter()
        {
            //this.BeginInvoke(new MethodInvoker(delegate
            //{
            Task.Run(() =>
            {
                string programnumber = "";
                string stepnumber = "";
                for (int i = 1; i < 51; i++)
                {
                    for (int j = 1; j < 16; j++)
                    {
                        //30 30 35 37 30 30 30 32 30 30 31 20 20 20 20 20 20 20 20 20 30 31 30 30 30 30 30 32 30 30 30 33 43 56 49 52 20 49 49 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 00 
                        //从ip：192.168.5.212:5056收到了数据：30 30 32 30 39 39 39 39 20 20 20 20 20 20 20 20 20 20 20 20 00 
                        //30 30 32 36 30 30 30 34 30 30 31 20 20 20 20 20 20 20 20 20 37 34 31 32 30 32 00 
                        
                        //程序号
                        string strtasknumber = i.ToString().PadLeft(3, '0');

                        string tasknumberhexstring = ConvertStringToHex(strtasknumber);

                        string tasknumberresult = InsertFormat(tasknumberhexstring, 2, " ") + "";
                        programnumber = tasknumberresult;

                        //步骤号
                        string strstepnumber = j.ToString().PadLeft(2, '0');

                        string stepnumberhexstring = ConvertStringToHex(strstepnumber);

                        string stepnumberresult = InsertFormat(stepnumberhexstring, 2, " ") + "";
                        stepnumber = stepnumberresult;
                        string message = "30 30 32 39 37 34 31 32 30 30 31 20 20 20 20 20 20 20 20 20 30 31 " + programnumber + " 30 32 " + stepnumber + " 00";

                        Debug.WriteLine("i->" + i + " " + "j->" + j + " " + "message->" + message);
                        SendOut(message);
                        Thread.Sleep(300);
                        if (contents.Length == 81 && contents == "30 30 32 36 30 30 30 34 30 30 31 20 20 20 20 20 20 20 20 20 37 34 31 32 30 32 00 ")
                        {
                            if (j == 1)
                            {
                                Debug.WriteLine("没有程序");
                                //清理不存在的数据
                                List<int> Dbtaskid = new List<int>();
                                DataTable dataTable = BLL.Bll.GetParameterTaskID();
                                for (int k = 0; k < dataTable.Rows.Count; k++)
                                {
                                    var taskid = System.Convert.ToInt32(dataTable.Rows[k][0]);
                                    Dbtaskid.Add(taskid);
                                }

                                List<int> tasklist = new List<int>();
                                for (int m = 0; m < Common.Batch.taskidlist.Count; m++)
                                {
                                    //string str1=str.Remove(0,i);
                                    var taskreultint = Common.Batch.taskidlist[m].ToString().Remove(0, 2);
                                    int inttask = System.Convert.ToInt32(taskreultint);
                                    tasklist.Add(inttask);
                                }
                                //找出控制没有，数据库有的差异
                                var diffList1 = Dbtaskid.Except(tasklist).ToList();
                                for (int h = 0; h < diffList1.Count; h++)
                                {
                                    int deletestatetask = BLL.Bll.DeleteParameterWithTaskIDData(diffList1[h].ToString());
                                    int deletestatestep = BLL.Bll.DeleteStepWithTaskIDData(diffList1[h].ToString());
                                    if (deletestatetask > 0)
                                    {
                                        Debug.WriteLine("删除多余的任务成功！");
                                    }
                                    if (deletestatestep > 0)
                                    {
                                        Debug.WriteLine("删除多余的步骤成功！");
                                    }
                                }
                                return;
                            }

                            for (int h = 0; h < Common.Batch.stepidlist.Count; h++)
                            {

                            }

                            //没有程序

                            break;
                        }
                        else
                        {
                            Debug.WriteLine("程序->" + i + " " + "步骤->" + j);
                        }
                    }

                    //for (int m = 0; m < Common.Batch.taskidlist.Count; m++)
                    //{
                    //    var taskdetail = Common.Batch.taskidlist[m];
                    //    string sArray = taskdetail.Replace("任务", "");

                    //    BLL.Bll.InsertParameterData(taskdetail, sArray.ToString());
                    //}

                    ////string newtaskstepstring = resultstrtaskid.ToString() + "," + resultstrstepid.ToString() + "," + laps + "," +
                    ////factspeeds.ToString() + "," + mintorques.ToString() + "," + maxtorques.ToString() + "," + safetorques.ToString() + "," +
                    ////anglethresholds.ToString() + "," + targettorques.ToString() + "," + minangles.ToString() + "," + maxangles.ToString() + "," +
                    ////safeangles.ToString() + "," + targetangles.ToString() + "," + "寻帽" + "," + tighteningType;
                    //for (int m = 0; m < Common.Batch.stepidlist.Count; m++)
                    //{
                    //    var taskdetail = Common.Batch.stepidlist[m];
                    //    string[] sArray = taskdetail.Split(',');
                    //}
                }

                //Common.Batch.stepidlist;
                //Common.Batch.taskidlist;

              

            });

            //}));
        }


        /// <summary>
        /// 调用程序
        /// </summary>
        /// <param name="tasknumber">任务号3位数不够补零</param>
        /// <param name="stepnumber">步骤号两位数不够补零</param>
        //public static void UseProgramIndexAndStepIndex(int tasknumber, int stepnumber)
        //{
        //    //任务号转为16进制字符串
        //    string strtasknumber = tasknumber.ToString().PadLeft(3, '0');

        //    string tasknumberhexstring = ConvertStringToHex(strtasknumber);

        //    string tasknumberresult = InsertFormat(tasknumberhexstring, 2, " ") + "";

        //    //步骤号转为16进制字符串
        //    string strstepnumber = stepnumber.ToString().PadLeft(2, '0');

        //    string stepnumberhexstring = ConvertStringToHex(strstepnumber);

        //    string stepnumberresult = InsertFormat(stepnumberhexstring, 2, " ") + "";


        //    SendOut("30 30 32 39 37 34 31 32 30 30 31 20 20 20 20 20 20 20 20 20 30 31 " + tasknumberresult + " 30 32 " + stepnumberresult + " 00");//
        //    //30 30 32 33 30 30 31 38 20 20 20 20 20 20 20 20 20 20 20 20 30 30 33 00
        //}

        /// <summary>
        /// 调用任务号
        /// </summary>
        /// <param name="tasknumber"></param>
        public static void InvokeTask(int tasknumber)
        {
            //任务号转为16进制字符串
            string strtasknumber = tasknumber.ToString().PadLeft(3, '0');

            string tasknumberhexstring = ConvertStringToHex(strtasknumber);

            string tasknumberresult = InsertFormat(tasknumberhexstring, 2, " ") + "";


            SendOut("30 30 32 33 30 30 31 38 20 20 20 20 20 20 20 20 20 20 20 20 " + tasknumberresult + " 00");//
        }


        /// <summary>
        /// 根据任务号下发指令
        /// </summary>
        /// <param name="tasknumber">任务号</param>
        public static void UseProgramIndex(int tasknumber)
        {

            Debug.WriteLine("ConnectionState->" + ConnectionState);
            tightenModels.Clear();
            ExecuteState = "";
            InvokeTask(tasknumber);//调用程序号

            ////DataTable paramerdata = BLL.Bll.GetParameterData();
            ////int index = tasknumber - 1;// parameterdataGridView.CurrentRow.Index;//选中任务的索引
            ////string content = paramerdata.Rows[index][0].ToString(); //parameterdataGridView.Rows[index].Cells[0].Value.ToString();
            ////DataTable dataTabletaskid = BLL.Bll.QueryContentWithTaskID(content);
            ////int taskid = System.Convert.ToInt32(dataTabletaskid.Rows[0][2]);
            DataTable dataTable = BLL.Bll.GetTaskWithStep(tasknumber);



            if (dataTable.Rows.Count > 0)
            {
                for (int i = 0; i < dataTable.Rows.Count; i++)
                {
                    //步骤
                    int Step = System.Convert.ToInt32(dataTable.Rows[i][2]);
                    //圈数
                    if (!string.IsNullOrEmpty(dataTable.Rows[i][3].ToString()))
                    {
                        double Lap = System.Convert.ToDouble(dataTable.Rows[i][3]);//目标角度/360
                    }

                    //速度
                    double Speed = 0; //System.Convert.ToDouble(dataTable.Rows[i][4]);

                    if (!string.IsNullOrEmpty(dataTable.Rows[i][4].ToString()))
                    {
                        Speed = System.Convert.ToDouble(dataTable.Rows[i][4]);
                    }

                    //最小扭矩
                    double MiniTorqueLength = 0; //System.Convert.ToDouble(dataTable.Rows[i][5]);

                    if (!string.IsNullOrEmpty(dataTable.Rows[i][5].ToString()))
                    {
                        MiniTorqueLength = System.Convert.ToDouble(dataTable.Rows[i][5]);
                    }

                    //最大扭矩
                    double MaxTorqueLength = 0; //System.Convert.ToDouble(dataTable.Rows[i][6]);

                    if (!string.IsNullOrEmpty(dataTable.Rows[i][6].ToString()))
                    {
                        MaxTorqueLength = System.Convert.ToDouble(dataTable.Rows[i][6]);
                    }

                    //安全扭矩
                    double SafeTorqueLength = 0; //System.Convert.ToDouble(dataTable.Rows[i][7]);

                    if (!string.IsNullOrEmpty(dataTable.Rows[i][7].ToString()))
                    {
                        SafeTorqueLength = System.Convert.ToDouble(dataTable.Rows[i][7]);
                    }

                    //安全扭矩
                    double Anglethreshold = 0; //System.Convert.ToDouble(dataTable.Rows[i][8]);

                    if (!string.IsNullOrEmpty(dataTable.Rows[i][8].ToString()))
                    {
                        Anglethreshold = System.Convert.ToDouble(dataTable.Rows[i][8]);
                    }

                    //角度阈值
                    double TargetTorqueLength = 0; //System.Convert.ToDouble(dataTable.Rows[i][9]);

                    if (!string.IsNullOrEmpty(dataTable.Rows[i][9].ToString()))
                    {
                        TargetTorqueLength = System.Convert.ToDouble(dataTable.Rows[i][9]);
                    }

                    //最小角度
                    double MiniAngle = 0; // System.Convert.ToDouble(dataTable.Rows[i][10]);

                    if (!string.IsNullOrEmpty(dataTable.Rows[i][10].ToString()))
                    {
                        MiniAngle = System.Convert.ToDouble(dataTable.Rows[i][10]);
                    }

                    //最大角度
                    double MaxAngle = 0; // System.Convert.ToDouble(dataTable.Rows[i][11]);

                    if (!string.IsNullOrEmpty(dataTable.Rows[i][11].ToString()))
                    {
                        MaxAngle = System.Convert.ToDouble(dataTable.Rows[i][11]);
                    }

                    //安全角度
                    double SafeAngle = 0; //System.Convert.ToDouble(dataTable.Rows[i][12]);

                    if (!string.IsNullOrEmpty(dataTable.Rows[i][12].ToString()))
                    {
                        SafeAngle = System.Convert.ToDouble(dataTable.Rows[i][12]);
                    }

                    //目标角度
                    double TargetAngle = 0; //System.Convert.ToDouble(dataTable.Rows[i][13]);

                    if (!string.IsNullOrEmpty(dataTable.Rows[i][13].ToString()))
                    {
                        TargetAngle = System.Convert.ToDouble(dataTable.Rows[i][13]);
                    }

                    //角度阈值

                    DataTable speedmaxdt = BLL.Bll.GetBatchMaxSpeed();
                    double factspeedmax = System.Convert.ToDouble(speedmaxdt.Rows[0][0].ToString());
                    //速度最高百分比130
                    double newspeed = Speed / factspeedmax;
                    double newspeeds = 0;

                    //double newpervalue = newper / 380;
                    double newpervalues = Math.Floor(newspeed * 100) / 100;
                    newspeed = newpervalues * 100;

                    if (newspeed > 130)
                    {
                        newspeed = 130;

                    }
                    else
                    {
                        newspeeds = newspeed; //Math.Round(Speed, 2);
                        newspeed = newspeeds;
                    }

                    //快速下旋

                    var steptypestring = dataTable.Rows[i][14].ToString();

                    if (steptypestring == "快速下旋")
                    {
                        ExecuteChangeData(tasknumber, Step, 0, 0, 0, 0, TargetTorqueLength, 0, 0, 0, 0, newspeed);
                    }
                    else
                    {
                        ExecuteChangeData(tasknumber, Step, MiniTorqueLength, MaxTorqueLength, SafeTorqueLength, Anglethreshold, TargetTorqueLength, MiniAngle, MaxAngle, SafeAngle, TargetAngle, newspeed);
                    }





                    //ExecuteChangeData(tasknumber, Step, MiniTorqueLength, MaxTorqueLength, SafeTorqueLength, Anglethreshold, TargetTorqueLength, MiniAngle, MaxAngle, SafeAngle, TargetAngle, Speed);

                    ExecuteState = "执行成功";
                }
            }
            else
            {
                ExecuteState = "没有步骤数据";
            }
        }


        public static void AnalayData()
        {
            //30 32 38 33 37 34 31 33 30 30 31 20 20 20 20 20 20 20 20 20 30 31 30 31 30 32 30 30 31 30 33 30 32 30 34 46 20 30 35 30 20
            //30 36 30 30 30 39 30 30
            //30 37 30 30 30 39 30 30
            //30 38 30 30 30 30 30 30
            //30 39 30 30 30 30 30 30
            //31 30 30 30 30 39 30 30
            //31 31 30 30 30 30 30 30
            //31 32 30 30 30 30 30 30
            //31 33 30 30 30 30 30 30
            //31 34 30 30 30 30 30 30
            //31 35 30 30 30 30 30 30
            //31 36 30 30 30 30 30 30
            //31 37 30 30 30 30 30 30
            //31 38 30 30 30 30 30 30
            //31 39 30 30 30 31 30 30
            //32 30 30 30 30 30 30 30
            //32 31 30 30 30 30 30 31
            //32 32 30 30 30 30 30 30
            //32 33 30 30 30 30 30 30
            //32 34 30 30 32 35 30 30 30 30 30 30 32 36 30 30 30 30 30 30 32 37 30 30 30 30 32 38 30 30 30 30 32 39 30 30 30 30 30 30 33 30 30 30 30 30 30 30 33 31 30 30 30 30 30 30 33 32 43 57 33 33 54 33 34 30 30 30 33 35 30 33 36 4E 6D 20 20 33 37 32 30 32 34 2D 30 35 2D 32 32 3A 31 34 3A 34 33 3A 33 34 00
        }


        /// <summary>
        /// 16进制转字符串
        /// </summary>
        /// <param name="hex"></param>
        /// <returns></returns>
        public static string HexToString(string hex)
        {
            // 将16进制字符串转换为字节数组
            byte[] bytes = new byte[hex.Length / 2];
            for (int i = 0; i < bytes.Length; i++)
            {
                bytes[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
            }

            // 使用UTF8编码将字节数组转换为字符串
            return Encoding.UTF8.GetString(bytes);
        }


        #endregion

        /// <summary>
        /// 终止线程
        /// </summary>
        public static void AutoSendAbort()
        {

            //关闭监听
            tcpclient.Close();
            try
            {
                if (thread != null)
                {
                    thread.Abort();
                    //jytAutoSend.Text = "循环发送";
                }
                ConnectionState = "未连接";
                BLL.Bll.UpdateCommunicateOnlineData("电批", "否");
            }
            catch (Exception ex)
            {
                Debug.WriteLine("AutoSendAbort->" + ex.Message.ToString());
            }
            isMonitor = false;
            //jytCom.Text = "连接";
            //设置控件可用
            //jytServerIPText.Enabled = true;
            //jytServerPort.Enabled = true;

            //try
            //{
            //    if (thread==null)
            //    {
            //        return;
            //    }
            //    isMonitor = false;
            //    thread.Abort();
            //}
            //catch (Exception ex)
            //{
            //    Debug.WriteLine(ex.Message.ToString());
            //}
            Debug.WriteLine("ConnectionState->" + ConnectionState);
        }

        /// <summary>
        /// 连接tcp
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void TCPConnection()
        {
            //BLL.Bll.TruncateParameterAndStep();//测试用，正式版会注释。
            //Thread.Sleep(10);
            Connection(ipaddress, ipport.ToString());
            GetHand();//握手指令
            SetResult();
            SetPhasesSubscribe();
            SetLastCurve();
            Thread.Sleep(10);
            AutoSend();//心跳发送

            Common.Batch.NewGetParameter();
        }

        public static void Reconnect()
        {
            stepidlist = new List<string>();//任务号，步骤号

            taskidlist = new List<string>();

            isMonitor = false;
            //BLL.Bll.TruncateParameterAndStep();//测试用，正式版会注释。
            //Thread.Sleep(10);
            Connection(ipaddress, ipport.ToString());
            GetHand();//握手指令
            SetResult();
            SetPhasesSubscribe();
            SetLastCurve();
            //AutoSend();//心跳发送
        }

    }
}
